看起来你应该使用the StrictMock模板修饰符 https://github.com/google/googletest/blob/master/googlemock/docs/CookBook.md#the-nice-the-strict-and-the-naggy。让我们使用这个简单的类和模拟:
struct Foo
{
virtual void function(int) {
}
};
struct MockFoo: public Foo
{
MOCK_METHOD1(function, void(int x));
};
让我们从练习该方法的基本测试开始:
TEST(MockTest, basic_one_expectation)
{
MockFoo foo;
EXPECT_CALL(foo, function(4));
Foo& foo1(foo);
foo1.function(3);
}
Output:
[ RUN ] MockTest.basic_one_expectation
unknown file: Failure
Unexpected mock function call - returning directly.
Function call: function(3)
Google Mock tried the following 1 expectation, but it didn't match:
mock-test.cpp:298: EXPECT_CALL(foo, function(4))...
Expected arg #0: is equal to 4
Actual: 3
Expected: to be called once
Actual: never called - unsatisfied and active
mock-test.cpp:298: Failure
Actual function call count doesn't match EXPECT_CALL(foo, function(4))...
Expected: to be called once
Actual: never called - unsatisfied and active
[ FAILED ] MockTest.basic_one_expectation (1 ms)
这是您已经考虑过的替代方案之一,但您不想要它,因为您还有其他测试,这些测试对函数是否被调用没有任何特定期望,并且您希望这些测试在函数被调用时失败反正。提醒一下,让我们看看尝试这样的测试时发生了什么:
TEST(MockTest, basic_no_expectation)
{
MockFoo foo;
Foo& foo1(foo);
foo1.function(3);
}
Output:
[ RUN ] MockTest.basic_no_expectation
GMOCK WARNING:
Uninteresting mock function call - returning directly.
Function call: function(3)
Stack trace:
[ OK ] MockTest.basic_no_expectation (1 ms)
我们收到警告,但测试仍然通过。这对你没有好处。我们来看看有什么效果StrictMock
has:
TEST(MockTest, strict_no_expectation)
{
::testing::StrictMock<MockFoo> foo;
Foo& foo1(foo);
foo1.function(3);
}
Output:
[ RUN ] MockTest.strict_no_expectation
unknown file: Failure
Uninteresting mock function call - returning directly.
Function call: function(3)
[ FAILED ] MockTest.strict_no_expectation (0 ms)
我们不必明确表示我们不希望调用该函数,但是当无论如何调用该函数时,测试都会失败。正是您想要的。
最后,让我们看看会发生什么StrictMock
在有的情况下are对函数参数的明确期望:
TEST(MockTest, strict_one_expectation)
{
::testing::StrictMock<MockFoo> foo;
EXPECT_CALL(foo, function(4));
Foo& foo1(foo);
foo1.function(3);
}
Output:
[ RUN ] MockTest.strict_one_expectation
unknown file: Failure
Unexpected mock function call - returning directly.
Function call: function(3)
Google Mock tried the following 1 expectation, but it didn't match:
mock-test.cpp:307: EXPECT_CALL(foo, function(4))...
Expected arg #0: is equal to 4
Actual: 3
Expected: to be called once
Actual: never called - unsatisfied and active
mock-test.cpp:307: Failure
Actual function call count doesn't match EXPECT_CALL(foo, function(4))...
Expected: to be called once
Actual: never called - unsatisfied and active
[ FAILED ] MockTest.strict_one_expectation (0 ms)
诊断显示参数不匹配的原因,就像原来的一样basic_one_expectation
测试如上所示。