C++ 如何使用gtest使用自定义密钥验证映射项?
我已经为我的地图编写了自定义密钥C++ 如何使用gtest使用自定义密钥验证映射项?,c++,c++11,c++17,googletest,C++,C++11,C++17,Googletest,我已经为我的地图编写了自定义密钥 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 {
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;
}
};
}
有了这些,我试着写一个测试
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" }
std::map my_map={{{“id”,“name”},“预期值”}
gtest说他没有找到匹配的。我迷路了。
由于在gtest的impl中大量使用了模板,我找不到任何帮助来调试它。
任何想法都将不胜感激。我在这里看到的第一个问题是您的
操作符==
没有常量
限定符。你需要这样的东西:
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
,然后再初始化std::map
您并没有解释在EXPECT_调用中执行的所有检查,但看起来您已经大致了解了如何使用进行容器验证
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")));
}
#包括
#包括
#包括
使用namespace::测试;
使用名称空间std;
结构自定义密钥{
字符串id;
弦扇;
布尔运算符==(常量自定义_键和其他)常量
{
//gtest需要我
返回id==other.id&§or==other.sector;
}
};
名称空间标准{
模板
无结构{
布尔运算符()
{
返回lhs.id
另外,我不明白您为什么需要matcher。请提供足够的代码,特别是能够运行此
EXPECT_CALL
(并重现错误)。谢谢您,我对advanced gtest解决方案不太熟悉,这正是我通过反复试验试图解决的问题。也许matcher在头顶上被剪掉了。
#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")));
}