【问题标题】:how to validate map items with custom key using gtest?如何使用 gtest 使用自定义键验证地图项?
【发布时间】:2021-05-26 11:41:45
【问题描述】:

我已经为我的地图编写了一个自定义键

struct custom_key {
  string id;
  string sector;

  bool operator==(const custom_key& other) {
    // I'm needed by gtest
    return id == other.id && sector == other.sector;
  }

};

我已经添加了少然后重载

namespace std
{
  template<> struct less<custom_key>
  {
    bool operator() (const custom_key& lhs, const custom_key& rhs) const
    {
      return lhs.id < rhs.id;
    }
  };
}

我还定义了我的匹配器

MATCHER_P(match_eq, value, "")
{
    return arg == value;
}

我试着写一个测试

EXPECT_CALL(
  *stats_,
  stats(
    AllOf(
      Field(&data,
        Contains(
          Pair(
            custom_key{"id", "name"},
            match_eq("expected_value")
          )
        )
      )
   )
);

我已经反对了

std::map<custom_key, std::string> my_map = { {"id", "name"}, "expected_value" }

并且 gtest 说他没有找到匹配项。我迷路了。 由于在 gtest 的 impl 中大量使用模板,我无法找到调试它的任何帮助。 任何想法将不胜感激。

【问题讨论】:

标签: c++ c++11 c++17 googletest


【解决方案1】:

我在这里看到的第一个问题是您的 operator== 没有 const 限定符。你需要这样的东西:

bool operator==(const custom_key& other) const {
    // I'm needed by gtest
    return id == other.id && sector == other.sector;
  }

下一个,

我已经针对 std::map my_map = { {"id", "name"}, "expected_value" }

运行它

这不会编译,你需要额外的大括号来初始化std::pair&lt;custom_key, std::string&gt;,然后初始化std::map

您没有解释您在 EXPECT_CALL 中执行的所有检查,但您似乎对使用 Contains 的容器验证有了大致的了解。

std::map 验证的完整解决方案如下所示:

#include <map>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
using namespace ::testing;
using namespace std;

struct custom_key {
    string id;
    string sector;

    bool operator==(const custom_key& other) const
    {
        // I'm needed by gtest
        return id == other.id && sector == other.sector;
    }
};

namespace std {
template <>
struct less<custom_key> {
    bool operator()(const custom_key& lhs, const custom_key& rhs) const
    {
        return lhs.id < rhs.id;
    }
};
}

TEST(MapValidation, 67704150)
{
    map<custom_key, string> my_map { { { "id", "name" }, "expected_value" } };
    EXPECT_THAT(my_map, Contains(Pair(custom_key { "id", "name" }, "expected_value")));
}

我也不明白为什么你需要匹配器。

【讨论】:

  • 谢谢你,我对高级 gtest 解决方案不太熟悉,这是我试图通过反复试验来解决的问题。也许 matcher 是需要削减的开销。
猜你喜欢
  • 1970-01-01
  • 2015-03-28
  • 1970-01-01
  • 2014-01-07
  • 1970-01-01
  • 1970-01-01
  • 2011-09-01
  • 2020-11-05
  • 2020-10-18
相关资源
最近更新 更多