// Filter.h/cpp
class Filter
{
public:
int readInt(int* value)
{
if (value == NULL)
return 0;
*value = 15; // some logical;
return 1;
}
};
// TestTee.h/.cpp
class TestTee
{
public:
Func1(Filter* f)
{
...
int val;
f->readInt(&val);
...
}
}
现在,我需要测试TestTee类,所以我模拟了类Filter
class MockFilter : public Filter
{
public:
MOCK_METHOD1(readInt, int(int*));
};
如何编写测试用例?
TEST_F(TestClass, Test1)
{
TestTee t;
MockFilter filter;
EXPECT_CALL(filter, readInt(_)).Times(1); // failed error: The mock function has no default action set, and its return type has no default value set." thrown in the test body.
/*
int val;
EXPECT_CALL(filter, readInt(&val)).Times(1);
Failed with the following error:
Expected: to be called once
Actual: never called - unsatisfied and active
*/
t.Func1(&filter);
}
所以,我的问题是
我不知道如何控制将在我的测试人员功能代码中调用的函数的输出参数。
有任何评论吗?很多。
答案 0 :(得分:0)
首先,不要忘记GoogleMock需要虚拟功能才能实际模拟它:
class Filter
{
public:
virtual int readInt(int* value)
{
if (value == NULL)
return 0;
*value = 15; // some logical;
return 1;
}
};
测试代码取决于您实际要测试的内容。如果你只想确保调用Filter :: readInt,那就足够了:
TEST_F(TestClass, Test1)
{
TestTee t;
MockFilter filter;
EXPECT_CALL(filter, readInt(_));
t.Func1(&filter);
}
(由于readInt具有内置的返回类型(int),因此GoogleMock应该能够在不抱怨的情况下找出默认返回值)
如果要确保仅调用readInt一次,请使用Times子句:
EXPECT_CALL(filter, readInt(_)).Times(1);
如果你想让readInt调用后的Testee代码在测试期间获得足够的返回值,即如果你想模拟模拟实函数的返回值,则使用Return子句作为返回值,并通过SetArgPointee子句传递输出值通过指针,或两者都这样:
EXPECT_CALL(filter, readInt(_)).WillOnce(DoAll(SetArgPointee<0>(15), Return(1)));