gpt4 book ai didi

c++ - 如何使用 gtest 构造检查存储在 vector 中的结构(字段)?

转载 作者:行者123 更新时间:2023-11-28 21:37:09 28 4
gpt4 key购买 nike

我想使用 gtest 检查存储在容器中的结构的有效性。一种方法是检索结构并与预期值进行比较。除了使用 gtest 构造之外,还有更好的方法吗?

auto receivedflexmessages = m_pugwintegration->getFlexMessages();
EXPECT_EQ(m_expectedflexmessages.size(), receivedflexmessages.size()) << "Mismatch in the received messages";

for (auto i = 0; i < receivedflexmessages.size(); i++)
{
EXPECT_EQ(m_expectedflexmessages[i].m_extId, receivedflexmessages[i].m_extId) << i << "Mismatch in extId";
EXPECT_EQ(m_expectedflexmessages[i].m_handle, receivedflexmessages[i].m_handle) << i << "Mismatch in handle";
EXPECT_EQ(m_expectedflexmessages[i].m_payloadLength, receivedflexmessages[i].m_payloadLength) << i << "Mismatch in payloadlength";

if (m_expectedflexmessages[i].m_payloadLength == receivedflexmessages[i].m_payloadLength)
{
for (auto j = 0; j < m_expectedflexmessages[i].m_payloadLength; ++j)
{
EXPECT_EQ(m_expectedflexmessages[i].m_pPayload[j], receivedflexmessages[i].m_pPayload[j]) << "Payload expected and received differ at index " << j;
}
}

最佳答案

有两种方法 - 都使用 gtest Container matchers :

  1. ::testing::ContainerEq 为容器 value_type
  2. 定义了相等运算符

参见:

using namespace ::testing;
EXPECT_THAT(receivedflexmessages, ContainerEq(m_expectedflexmessages));

// that is - just 1 line not counting operator == ()
// for decltype(m_expectedflexmessages)::value_type
  1. ::testing::ElementsAreArray 并在 m_expectedflexmessages
  2. 之上构建匹配器 vector

using namespace ::testing;
using ElementType = decltype(receivedflexmessages)::value_type;
std::vector<Matcher<ElementType >> m_expectedflexmessagesMatchers;

for (auto&& expectedMessage : m_expectedflexmessages)
{
m_expectedflexmessagesMatchers.push_back(AllOf(
Field(&ElementType::m_extId, expectedMessage.m_extId),
Field(&ElementType::m_handle, expectedMessage.m_handle),
Field(&ElementType::m_payloadLength, expectedMessage.m_payloadLength),
Field(&ElementType::m_pPayload, ElementsAreArray(expectedMessage.m_pPayload, expectedMessage.m_payloadLength)));
}
EXPECT_THAT(receivedflexmessages, ElementsAreArray(m_expectedflexmessagesMatchers));


我不建议使用最短的形式 EXPECT_EQ(m_expectedflexmessages, receivedflexmessages)(假设你有 ElementType 的运算符 ==)——因为你会丢失第一个不匹配元素索引的信息(和大小)当测试失败时。使用上述匹配器 - 此信息将显示在屏幕上。

此外,您可能希望实现 PrintTo(const ElementType&, std::ostream* os) { ... } 以更好地呈现无法比较的内容

关于c++ - 如何使用 gtest 构造检查存储在 vector 中的结构(字段)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57136116/

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