Google Mock:如何测试此代码?

时间:2012-08-21 15:23:09

标签: c++ mocking googletest googlemock

我使用Google Mock通过模拟Xyz::xyz_func编写了以下代码来测试Abc::abc_func

#include <iostream>
#include "gmock/gmock.h"
#include "gtest/gtest.h"

using namespace std;
using ::testing::_;
using ::testing::Return;

class Abc
{
    public:
        virtual ~Abc() {}

        virtual bool abc_func(int arg)  = 0;
};

class MockAbc : public Abc
{
    public:
        virtual ~MockAbc() { }

        MOCK_METHOD1(abc_func,  bool(int arg));
};

class AbcImpl : public Abc
{
    public:
        virtual bool abc_func(int arg)
        {
            cout << arg << " :: " << __FILE__ << " :: " << __LINE__ << endl;
            return true;
        }
};

class Xyz : public AbcImpl
{
    public:
        virtual ~Xyz() {}
        virtual bool xyz_func()
        {
            AbcImpl obj;
            return obj.abc_func(1);
        }
};

TEST(AbcTest, func_success)
{
    MockAbc *mock = new MockAbc();

    EXPECT_CALL(*mock,  abc_func(_)).WillOnce(Return(true));

    Xyz test;

    EXPECT_TRUE(test.xyz_func());

    delete mock;
}

int main(int argc, char** argv)
{
    ::testing::InitGoogleMock(&argc, argv);
    return RUN_ALL_TESTS();
}

但我得到以下错误。我想知道如何告诉Xyz类调用abc_func的mock而不是实际的实现。你能帮我吗?

1 :: ./gmock_test.cpp :: 30
./gmock_test.cpp:50: Failure
Actual function call count doesn't match EXPECT_CALL(*mock, abc_func(_))...
         Expected: to be called once
           Actual: never called - unsatisfied and active

1 个答案:

答案 0 :(得分:2)

您正在创建类型为MockAbc的模拟对象,但您从未使用它。从您的代码中可以看出,您希望自己创建的MockAbc实例能够自动替换您在AbcImpl中明确创建的Xyz::xyz_func对象。

您需要做的是使用dependency inversion来允许在运行时指定xyz_func使用的对象。

您不需要Xyz继承AbcImplAbc


两种可能的解决方案:

class Xyz {
public:
    explicit Xyz(Abc& obj) : 
        obj(&) {
    }

    virtual bool xyz_func() {
        return obj->abc_func(1);
    }
private:
    Abc* obj;
};

class Xyz {
public:
    virtual bool xyz_func(Abc& obj) {
        return obj->abc_func(1);
    }
};