Reputation: 491
i have this simple code
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);
}
};
Now I would like to test the SimpleMethod
and mock the SimpleStruct
like this:
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
}
How can I assure that the mocked method is being used?
My question is related to this Question, but I cannot change the use of SimpleStruct in the signature of SimpleMethod, because in my case my signature is defined through the jni.
Upvotes: 0
Views: 1335
Reputation: 2859
Gmock can mock only virtual
functions, so in order for it to work add()
should be declared virtual. But it only necessary for it to be virtual for unit testing, so you can do something like:
#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;
}
};
Just make sure that tested code doesn't depend from fact that SimpleStruct is POD.
Upvotes: 1