Google Mock:将指针传递给模拟对象,但方法调用仍在调用真实方法

Google Mock: passing pointer to mock object, but method call is still calling real method

我有这个简单的代码

struct SimpleStruct {
    int add(int a, int b) {
        return a+b;
    }
};

class SimpleClass {
public:
    int SimpleMethod(SimpleStruct* simpleStruct, int a, int b) {
        return simpleStruct->add(a, b);
    }
};

现在我想像这样测试 SimpleMethod 和模拟 SimpleStruct

struct MockSimpleStruct : public SimpleStruct {
    MOCK_METHOD(int, add, (int, int), (const));
};


TEST(Test_Calculation, simpleStruct) {
    MockSimpleStruct mockSimpleStruct;

    EXPECT_CALL(mockSimpleStruct, add(_,_)).Times(2).WillOnce(DoAll(Return(7))).WillOnce(DoAll(Return(7)));
    EXPECT_EQ(7, mockSimpleStruct.add(2, 3)); // working fine

    SimpleClass simpleClass;
    int result = simpleClass.SimpleMethod(&mockSimpleStruct, 2, 3); // not working: inside SimpleMethod the real add method is called

    EXPECT_EQ(7, result); // fails
}

如何确保正在使用模拟方法?

我的问题与this Question有关,但我无法更改SimpleMethod签名中SimpleStruct的使用,因为在我的例子中我的签名是通过jni定义的。

Gmock 只能模拟 virtual 函数,因此为了使其正常工作,应该将 add() 声明为虚拟函数。但是它只需要在单元测试中是虚拟的,所以你可以这样做:

#ifdef UNDER_TEST
#define TEST_VIRTUAL virtual
#else
#define TEST_VIRTUAL
#endif

struct SimpleStruct {
    TEST_VIRTUAL int add(int a, int b) {
        return a+b;
    }
};

只需确保测试代码不依赖于 SimpleStruct 是 POD 的事实。