der*_*ris 2 c++ googletest googlemock
我知道这个问题已被问过多次,但没有一个答案对我有用。这是我想测试的模拟函数:
MOCK_METHOD2(sendInternal, void(uint8_t data[], uint8_t size));
Run Code Online (Sandbox Code Playgroud)
测试是这样的
uint8_t expectedMessageData[3] = { 0x08, 0xda, 0xff };
EXPECT_CALL(*serverFake, sendInternal(testing::_,3))
.With(testing::Args<0, 1>(ElementsAre(0x08, 0xda, 0xff)))
.Times(1);
Run Code Online (Sandbox Code Playgroud)
但这导致
预期参数:是一个元组,其字段 (#0, #1) 有 2 个元素,其中元素 #0 等于 '\b' (8),元素 #1 等于 '\xDA' (218) 实际:don' t 匹配,其字段 (#0, #1) 为 (0x7fcfd9500590, '\x11' (3)),有 3 个元素
对我来说,Gmock 似乎会比较参数而不是数组的元素。
我什至构建了一个自定义匹配器:
MATCHER_P2(HasBytes, bytes, size, "") {
uint8_t * dataToCheck = arg;
bool isMatch = (memcmp(dataToCheck, bytes, size) == 0);
return isMatch;
}
Run Code Online (Sandbox Code Playgroud)
我可以看到(在调试时) 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;
}
Run Code Online (Sandbox Code Playgroud)
其次,根据this topicElementsAre,官方不支持C风格数组。如果您确实无法更改方法签名,并且您确实希望在原始数组上使用,则可以使用该主题中提出的 hack。干杯。ElementsAre
| 归档时间: |
|
| 查看次数: |
7415 次 |
| 最近记录: |