如何在MOCK中的不同类的虚拟函数上使用MOCK_METHOD



我正试图使用EXPECT_CALL来设置函数的返回值,该函数位于不同于mock类继承的类中。

在下面的片段中,我想知道是否有一种方法可以通过UnitTest类的bar对象在单元测试中的Bar的公共函数someFunction()上使用EXPECT_CALL,但它似乎出错了。

我知道的一件事是,我需要对someFunction使用MOCK_METHOD来覆盖它以期望EXPECT_CALL,但不确定在Mock类中该怎么做?

// Bar.hpp
class Bar
{
public:
virtual bool someFunction();
};
// Foo.hpp
namespace sw::foo_state
{
class Foo
{
Bar _bar;

public:
Foo(Bar&& bar) : _bar(std::move(bar)) {}

void TestFunction()
{
_bar.someFunction();
}
};
};
// MockClass.hpp
namespace sw
{
class Mock : public foo_state::Foo
{
Mock(Bar&& bar) : Foo(std::move(bar)) {}
};
};
// UnitTest.cpp
using namespace sw::foo_state;
class UnitTest
{
public:
Bar bar;
auto ptr = std::make_unique<Mock>(std::move(bar));   
};

TEST_F(UnitTest, Test)
{
EXPECT_CALL(bar, someFunction()).WillOnce(Return(true)); //  error: ‘class sw::foo_state::Bar’ has no member named ‘gmock_someFunction’; did you mean ‘someFunction’?
ptr->TestFunction();
}

编辑:

您只需要更改class Foo构造函数以接受指针或引用,就可以利用class Bar多态性:

class Bar
{
public:
virtual bool someFunction()
{
return true;
}
};
class Foo
{
public:
Foo(Bar& bar): _bar{ bar} {}
void TestFunction()
{
std::cout << _bar.someFunction() << std::endl;
}
private:
Bar& _bar;  // can also be std::unique_ptr<Bar> if you prefer to own the object
};
struct MockBar : public Bar
{
MOCK_METHOD0(someFunction, bool());
};
using testing::Return;
TEST(xxx, yyy)
{
MockBar mBar;
// ON_CALL(mBar, someFunction()).WillByDefault(Return(false));  // if you don't want to force expectation
EXPECT_CALL(mBar, someFunction()).WillOnce(Return(false));
Foo foo(mBar);
foo.TestFunction();
}

最新更新