Uni*_*qus 4 c++ unit-testing googletest googlemock
我正在使用谷歌模拟1.7.0与谷歌测试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 Code Online (Sandbox Code Playgroud)
但是当我运行测试时它失败并显示以下消息:
[ 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)
Run Code Online (Sandbox Code Playgroud)
有什么我误解,或做错了,或者这是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"));
Run Code Online (Sandbox Code Playgroud)
这将需要两个调用 - 一个以"STAT"作为参数,另一个使用"QUIT".或这个:
EXPECT_CALL(testMock, command(_));
EXPECT_CALL(testMock, command("STAT")).Times(1).WillOnce(Return("+OK 1 2\r\n"));
Run Code Online (Sandbox Code Playgroud)
期望一个带参数的单个参数"STAT"和另一个带有参数的调用"STAT".在这种情况下,期望的顺序是重要的,因为EXPECT_CALL(testMock, command(_))它将满足任何调用,包括"STAT"如果它出现在另一个期望之后.