gpt4 book ai didi

c++ - 匹配数组的谷歌模拟

转载 作者:太空宇宙 更新时间:2023-11-04 07:57:06 25 4
gpt4 key购买 nike

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

  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 风格的数组。 .如果您确实无法更改您的方法签名,并且您确实希望在原始数组上使用 ElementsAre,则可以使用该主题中提出的 hack。干杯。

关于c++ - 匹配数组的谷歌模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49283176/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com