Gmock 只期待一个特定的调用

Gmock only expect a specific call

我有一个 C++ class 我正在尝试使用 GMock 进行测试。我有以下模拟 class:

class MyTestMock
{
    public:
        MOCK_METHOD1(myCoolMethod, int(const char*));
        MOCK_METHOD1(myCoolMethod, int(string));
}

然后在我的测试中发生以下情况:

MyTestMock myMock;
if ( myMock.myCoolMethod("stuff") )
{
    // Stuff I don't care about, don't want to execute
}
if ( myMock.myCoolMethod("moarStuff") )
{
    // More stuff I don't care about, don't want to execute
}
if ( myMock.myCoolMethod("foo") )
{
    // This I care about and want to execute
}

我想做的是允许前两次调用是无趣的调用,return 是整数的默认值 0,而我在第三次调用 [=26= 时设置了特定的期望] 1. 这是我的尝试:

EXPECT_CALL(myMock, myCoolMethod(TypedEq<const char *>("foo"))).WillOnce(Return(1));

然而,这最终导致测试失败。如果我这样做:

EXPECT_CALL(myMock, myCoolMethod(Matcher<const char *>(_))).WillRepeatedly(Return(0));
EXPECT_CALL(myMock, myCoolMethod(TypedEq<const char *>("foo"))).WillOnce(Return(1));

我的测试通过了。我试图在旧的、庞大的、整体式的代码库上尽可能轻松地进行单元测试,所以我真的不需要额外的魔法线来告诉它 return 默认值。关于如何在不影响我的测试的情况下只用一个期望来做到这一点,我有什么想法吗?

我想我的答案不是很 "expected" 来测试 "an old, massive, monolithic-style codebase" 可能有大量这样的 CoolMethods...,但是,不幸的是 google -模拟作品。你可以在他们的 FAQ:

中读到

Having an ON_CALL in the set-up part of a test doesn't mean that the calls are expected. If there's no EXPECT_CALL and the method is called, it's possibly an error. If we quietly let the call go through without notifying the user, bugs may creep in unnoticed.

"default" ON_CALL 也是如此 - 我的意思是当你没有明确写 ON_CALL 因为类型的默认值(在你的情况下 0 int) 完全可以。

我的建议是始终将这种一般期望放在测试套件的 SetUp 函数中 - 这样您的测试用例就不会因许多神奇的期望而超载:

class MyTestSuite : public ::testing::Test
{
protected:
    MyTestMock myMock;
    void SetUp() override
    {
        EXPECT_CALL(myMock, myCoolMethod(Matcher<const char *>(_))).WillRepeatedly(Return(0));
    }   
};

这样你只有一个地方有 "annoying" 行,你的测试用例是 "clear":

TEST_F(MyTestSuite, shallDoSomethingWhenCoolMethodAcceptsFoo)
{
   EXPECT_CALL(myMock, myCoolMethod(TypedEq<const char *>("foo"))).WillOnce(Return(1));
}
TEST_F(MyTestSuite, shallDoSomethingElseWhenCoolMethodAcceptsMoarStuff)
{
   EXPECT_CALL(myMock, myCoolMethod(TypedEq<const char *>("moarStuff"))).WillOnce(Return(1));
}