[英]How do I unit test and check the contents of a vector object of a custom struct using google mock?
如果结构是
struct Point{
double x;
double y;
};
和 function 的 output 是vector<Point>
并且大小为 10,我如何编写 Google Test 或 Google Mock(我认为这更适合)来验证向量的内容? 我可以在原始字符串中写入预期的 output。
首先:手动编写断言,逐个元素检查大小和内容是很好的:
std::vector<Point> MethodReturningVector();
TEST(MethodReturningVectorTest, CheckSizeAndFirstElementTest) {
const auto result = MethodReturningVector();
ASSERT_EQ(10, result.size());
ASSERT_NEAR(42.f, result[0].x, 0.001f);
ASSERT_NEAR(3.141592.f, result[0].y, 0.001f);
}
一旦你写了很多不同的测试,你就会看到一个共同的断言模式,然后你可以重构你的测试,一切都会自然而然地就位。
但是正如您提到的 GMock,确实有一些 GMock 技术可以使用。 有内置的匹配器来匹配类 STL arrays(我说类 STL 是因为它只需要开始和结束),例如ElementsAre
( ElementsAreArray
也存在)。 但是,它们要求数组中的元素可以进行比较。 这反过来要求为您的类型定义operator==
(很少),因为默认的Eq
匹配器正在使用它。 您可以使用其他内置匹配器(如AllOf
(匹配器的聚合器)和Field
(匹配结构的给定字段))为自定义类型定义自己的匹配器。 匹配器可以合并。 有关完整图片,请参见(工作示例):
struct Point{
double x;
double y;
};
std::vector<Point> MethodReturningVector() {
std::vector<Point> result(3);
result[0] = Point{42.f, 3.141592f};
return result;
}
MATCHER_P(Near, expected, "...") {
constexpr auto allowed_diff = 0.001f; // allow small diference
if (!(expected - arg <= allowed_diff && arg <= expected + allowed_diff)) {
*result_listener << "expected: " << expected << ", actual: " << arg;
return false;
}
return true;
}
auto MatchPoint(Point p) {
return testing::AllOf(testing::Field(&Point::x, Near(p.x)),
testing::Field(&Point::y, Near(p.y)));
}
TEST(MethodReturningVectorTest, TestOneElement)
{
const auto result = MethodReturningVector();
ASSERT_EQ(result.size(), 3);
ASSERT_THAT(result[0], MatchPoint(Point{42.f, 3.1415}));
}
TEST(MethodReturningVectorTest, TestWholeArray)
{
const auto result = MethodReturningVector();
ASSERT_THAT(result, testing::ElementsAre(
MatchPoint(Point{42.f, 3.1415f}),
MatchPoint(Point{0.f, 0.f}),
MatchPoint(Point{0.f, 0.f})));
}
我强烈建议你从 GTest/GMock cookbook 等开始。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.