Google 模拟匹配数组

Google Mock matching an array

我知道这个问题已被多次询问,但 none 的答案对我有用。 这是我要测试的模拟函数:

  MOCK_METHOD2(sendInternal, void(uint8_t data[], uint8_t size));

测试是这样的

    uint8_t expectedMessageData[3] = { 0x08, 0xda, 0xff };


    EXPECT_CALL(*serverFake, sendInternal(testing::_,3))
            .With(testing::Args<0, 1>(ElementsAre(0x08, 0xda, 0xff)))
            .Times(1);

但这会导致

Expected args: are a tuple whose fields (#0, #1) has 2 elements where element #0 is equal to '\b' (8), element #1 is equal to '\xDA' (218) Actual: don't match, whose fields (#0, #1) are (0x7fcfd9500590, '\x11' (3)), which has 3 elements

对我来说,Gmock 似乎会比较参数而不是数组的元素。

我什至构建了一个自定义匹配器:

MATCHER_P2(HasBytes, bytes, size, "") {
    uint8_t * dataToCheck = arg;
    bool isMatch = (memcmp(dataToCheck, bytes, size) == 0);
    return isMatch;
}

我可以看到(在调试时)isMatch == true 但测试仍然失败。

请帮忙!

首先,我没有复现你的问题。以下示例编译并测试通过:

class ServerFake {
  public:
    MOCK_METHOD2(sendInternal, void(uint8_t data[], uint8_t size));
};

// If only possible, I recommend you to use std::vector instead of raw array
class ServerFake2 {
  public:
    MOCK_METHOD1(sendInternal, void(std::vector<uint8_t> data));
};

MATCHER_P2(HasBytes, bytes, size, "") {
    // unnecessary assignment, I think ...
    uint8_t * dataToCheck = arg;
    bool isMatch = (memcmp(dataToCheck, bytes, size) == 0);
    return isMatch;
}

using ::testing::ElementsAre;

TEST(xxx, yyy) {

    ServerFake* serverFake = new ServerFake;
    ServerFake2* serverFake2 = new ServerFake2;

    uint8_t expectedMessageData[3] = { 0x08, 0xda, 0xff };
    std::vector<uint8_t> expectedMessageData2({ 0x08, 0xda, 0xff });

    EXPECT_CALL(*serverFake, sendInternal(HasBytes(expectedMessageData, 3), 3)).Times(1);
    // the code below compiles and passes as well! However, I didn't check why;
    // EXPECT_CALL(*serverFake, sendInternal(testing::_,3))
    //     .With(testing::Args<0, 1>(ElementsAre(0x08, 0xda, 0xff)))
    //     .Times(1);
    serverFake->sendInternal(expectedMessageData, 3);


    // much better, do like this!
    EXPECT_CALL(*serverFake2, sendInternal(ElementsAre(0x08, 0xda, 0xff))).Times(1);
    serverFake2->sendInternal(expectedMessageData2);


    delete serverFake;
    delete serverFake2;
}

其次,根据this topicElementsAre官方不支持C-style数组。如果您确实无法更改方法签名,并且确实希望在原始数组上使用 ElementsAre,则可以使用该主题中提出的技巧。干杯。