GoogleMock:如何验证输入参数 w.r.t 调用次数?

GoogleMock: How to validate input parameters w.r.t number of invocations?

我正在使用 GoogleTest and GoogleMock 为 C++ class 编写单元测试。我当前的代码如下所示:

MockNetConnector* connector = new MockNetConnector();
NetClient* client = new NetClient(connector);

TEST_F(NetClientTest, connect)
{
    EXPECT_CALL(*connector, attempt_connect(_,_)).Times(3)
        .WillOnce(Return(false))
        .WillOnce(Return(false))
        .WillOnce(Return(true));

    std::string srv_list = "127.0.0.1:30001,127.0.0.2:30002,127.0.0.3:30003";
    bool is_connected = client->connect(srv_list);

    ASSERT_TRUE(is_connected);
}

如您所见,(*connector).attempt_connect(_,_) 当前不验证输入参数。现在我希望它在每次调用时验证输入,即输入应该是 (127.0.0.x, 3000x) 用于调用 x-th.

我知道如何验证固定值的参数,例如attempt_connect(StrEq("127.0.0.1"),Eq(30001)),但不知道如何验证因调用而异的参数。

我找到了问题的解决方案,但可能不是最好的。

首先定义一个全局变量叫postfix:

static int postfix = 0;

写自定义 matchers:

MATCHER(ValidateIP, "")
{
    std::string expected_ip = "127.0.0." + to_string(::ip_postfix);

    return (expected_ip == arg);
}

MATCHER(ValidatePort, "")
{
    int expected_port = 30000 + ::port_postfix;

    return (expected_port == arg);
}

编写自定义 action,每次调用后增加 postfix

ACTION(IncreasePostfix)
{
    ::postfix++;
}

将匹配器应用于期望:

EXPECT_CALL(*connector, attempt_connect(ValidateIP(),ValidatePort())).Times(3)
    .WillOnce(DoAll(IncreasePostfix(), Return(false)))
    .WillOnce(DoAll(IncreasePostfix(), Return(false)))
    .WillOnce(DoAll(IncreasePostfix(), Return(true)));

要使 postfix 对每个测试单独生效,请在测试开始前重置它们(即在 NetClientTest::SetUp() 内)

class NetClientTest : public testing::Test
{
    virtual void SetUp() {
        ::postfix = 1;
    }

    // other methods
};