Google Mock: why NiceMock does not ignore unexpected calls?

柔情痞子 提交于 2019-12-07 07:56:37

问题


I am using Google Mock 1.7.0 with Google Test 1.7.0. The problem is when I use NiceMock I get test failures because of unexpected mock function call (which should be ignored by NiceMock as per Google Mock documentation). The code looks like this:

// 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");
}

But when I run the test it fails with the following message:

[ 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)

It there something that I misunderstand, or doing wrong, or that is a bug in Google Mock framework?


回答1:


Distinctions between NiceMock and StrictMock only come into play if there are no expectations set on the method. But you you have told Google Mock to expect a single call to command with the argument "QUIT". When it sees the second call, it complains.

Maybe you meant this:

EXPECT_CALL(testMock, command("STAT")).Times(1).WillOnce(Return("+OK 1 2\r\n"));
EXPECT_CALL(testMock, command("QUIT"));

which will expect two calls - one with "STAT" as a parameter, and one with "QUIT". Or this:

EXPECT_CALL(testMock, command(_));
EXPECT_CALL(testMock, command("STAT")).Times(1).WillOnce(Return("+OK 1 2\r\n"));

which will expect a single one with the parameter "STAT" and one other call with a parameter other than "STAT". The order of expectations in this case is important as EXPECT_CALL(testMock, command(_)) will satisfy any calls, including the one with "STAT" if it comes after the other expectation.



来源:https://stackoverflow.com/questions/24923688/google-mock-why-nicemock-does-not-ignore-unexpected-calls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!