我正在将Google Mock 1.7.0与Google Test 1.7.0一起使用。问题是当我使用NiceMock时,由于意外的模拟函数调用(根据Google Mock文档应被NiceMock忽略)而导致测试失败。代码看起来像这样:
// Google Mock test
#include <gtest/gtest.h>
#include <gmock/gmock.h>
using ::testing::Return;
using ::testing::_;
class TestMock {
public:
TestMock() {
ON_CALL(*this, command(_)).WillByDefault(Return("-ERR Not Understood\r\n"));
ON_CALL(*this, command("QUIT")).WillByDefault(Return("+OK Bye\r\n"));
}
MOCK_METHOD1(command, std::string(const std::string &cmd));
};
TEST(Test1, NiceMockIgnoresUnexpectedCalls) {
::testing::NiceMock<TestMock> testMock;
EXPECT_CALL(testMock, command("STAT")).Times(1).WillOnce(Return("+OK 1 2\r\n"));
testMock.command("STAT");
testMock.command("QUIT");
}
但是当我运行测试时,它失败并显示以下消息:
[ RUN ] Test1.NiceMockIgnoresUnexpectedCalls
unknown file: Failure
Unexpected mock function call - taking default action specified at:
.../Test1.cpp:13:
Function call: command(@0x7fff5a8d61b0 "QUIT")
Returns: "+OK Bye\r\n"
Google Mock tried the following 1 expectation, but it didn't match:
.../Test1.cpp:20: EXPECT_CALL(testMock, command("STAT"))...
Expected arg #0: is equal to "STAT"
Actual: "QUIT"
Expected: to be called once
Actual: called once - saturated and active
[ FAILED ] Test1.NiceMockIgnoresUnexpectedCalls (0 ms)
[我误解或做错了什么,还是Google Mock框架中的错误?
[NiceMock和StrictMock之间的区别仅在该方法没有设定期望时起作用。但是您已经告诉Google Mock期望使用参数command
来单独调用"QUIT"
。看到第二个电话时,就会抱怨。
也许你是这个意思:
EXPECT_CALL(testMock, command("STAT")).Times(1).WillOnce(Return("+OK 1 2\r\n"));
EXPECT_CALL(testMock, command("QUIT"));
这将进行两次调用-一个以“ STAT”作为参数,另一个以“ QUIT”作为参数。或这个:
EXPECT_CALL(testMock, command(_));
EXPECT_CALL(testMock, command("STAT")).Times(1).WillOnce(Return("+OK 1 2\r\n"));
这将期望有一个参数为"STAT"
的单个呼叫,而另一个呼叫将为参数"STAT"
以外的呼叫。在这种情况下,期望的顺序很重要,因为EXPECT_CALL(testMock, command(_))
将满足任何调用,包括"STAT"
的调用(如果它在另一个期望之后)。