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

时间:2016-12-27 02:41:02

标签: c++ unit-testing mocking googletest googlemock

我还是Google Mock的新手,所以我一边学习。我刚刚添加了一些单元测试,而且我遇到了一个问题,我无法使ON_CALL()正确地存在从方法中调用的方法。

以下代码概述了我的内容;

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();
}

我想我必须在这里遗漏一些明显的东西,任何人都可以帮忙吗?谢谢!

1 个答案:

答案 0 :(得分:1)

您必须将方法标记为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());
}

现在可以使用