gpt4 book ai didi

C++ Google Mock - EXPECT_CALL() - 期望在不直接调用时不起作用

转载 作者:行者123 更新时间:2023-11-30 03:35:24 25 4
gpt4 key购买 nike

我对 Google Mock 还是很陌生,所以边学边学。我刚刚添加了一些单元测试,但遇到了一个问题,我无法让 ON_CALL() 正确地 stub 从方法内部调用的方法。

下面的代码概述了我所拥有的;

class simpleClass
{
public:
bool simpleFn1() { return simpleFn2(); }
virtual bool simpleFn2() { return FALSE; }
}

在我的单元测试中我有:

class simpleClassMocked : public simpleClass
{
private:
MOCK_METHOD0(simpleFn2, bool());
}

class simpleClassTests : public ::testing::Test
{
}

TEST_F(simpleClassTests, testSimpleFn2)
{
shared_ptr<simpleClassMocked> pSimpleClass = shared_ptr< simpleClassMocked >(new simpleClassMocked());

ON_CALL(*pSimpleClass, simpleF2()).WillByDefault(Return(TRUE));

// This works as expected - simpleFn2() gets stubbed
pSimpleClass->simpleFn2();

// This doesn't work as expected - when simpleFn1 calls simpleFn2 it's not the stubbed expectation???
pSimpleClass->simpleFn1();
}

我想我一定遗漏了一些明显的东西,有人可以帮忙吗?谢谢!

最佳答案

您必须将该方法标记为virtual 并在simpleClassMocked 类中添加相应的MOCK 函数

class simpleClass
{
public:
virtual bool simpleFn1() { return simpleFn2(); }
virtual bool simpleFn2() { return FALSE; }
}

此外,您需要将 Mock 方法放在 public 区域

class simpleClassMocked : public simpleClass
{
public:
MOCK_METHOD0(simpleFn2, bool());
MOCK_METHOD0(simpleFn1, bool());
}

现在可以了

关于C++ Google Mock - EXPECT_CALL() - 期望在不直接调用时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41338367/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com