【问题标题】:Google Mock: why NiceMock does not ignore unexpected calls?Google Mock:为什么 NiceMock 不忽略意外调用?
【发布时间】:2014-09-15 10:00:17
【问题描述】:

我将 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 框架中的错误?

【问题讨论】:

    标签: c++ unit-testing googletest googlemock


    【解决方案1】:

    NiceMock 和 StrictMock 之间的区别只有在没有对方法设置期望的情况下才会发挥作用。但是您已经告诉 Google Mock 期望使用参数 "QUIT"command 进行一次调用。当它看到第二个调用时,它会抱怨。

    也许你的意思是这样的:

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

    【讨论】:

    • 如果我不知道该方法要调用多少次,是否可以使用EXPECT_CALL(testMock, command(_)).Times(AnyNumber())?我只对它使用 'STAT' 参数只调用一次这一事实感兴趣。
    • @Uniqus - 是的,绝对的。
    猜你喜欢
    • 1970-01-01
    • 2021-09-13
    • 2014-01-15
    • 1970-01-01
    • 2013-04-24
    • 1970-01-01
    • 1970-01-01
    • 2018-03-13
    • 1970-01-01
    相关资源
    最近更新 更多