看起来你应该使用the StrictMock
template modifier。让我们用这个简单的类和模拟:
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);
}
输出:
[ 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)
这就是你的选择之一已经考虑过了,但是你不需要它,因为你有其他的测试对函数是否被调用没有任何特别的期望,并且你想让这些测试失败,如果函数变成了c无论如何。作为提醒,让我们来看看发生了什么,当我们试图这样一个测试:
TEST(MockTest, basic_no_expectation)
{
MockFoo foo;
Foo& foo1(foo);
foo1.function(3);
}
输出:
[ 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
有:
TEST(MockTest, strict_no_expectation)
{
::testing::StrictMock<MockFoo> foo;
Foo& foo1(foo);
foo1.function(3);
}
输出:
[ 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
发生在有是为函数的参数明确的预期:
TEST(MockTest, strict_one_expectation)
{
::testing::StrictMock<MockFoo> foo;
EXPECT_CALL(foo, function(4));
Foo& foo1(foo);
foo1.function(3);
}
输出:
[ 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
测试一样。
哦,是的!就是这样 – haelix 2014-09-26 17:10:10