Google Mock:为什么NiceMock不会忽略意外的来电?

时间:2014-07-24 01:25:16

标签: 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      ] 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框架中的错误?

1 个答案:

答案 0 :(得分:6)

如果没有对方法设定期望,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"));

预计有两个电话 - 一个用&#34; STAT&#34;作为参数,和#34; QUIT&#34;。或者这个:

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"的调用,如果它出现在另一个期望之后。