使用C ++ Catch测试浮点std :: vector [英] Test floating point std::vector with C++ Catch
本文介绍了使用C ++ Catch测试浮点std :: vector的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Catch C ++单元测试框架中是否有可能比较基于浮点类型的std :: vector?我知道我可以比较两个容器和每个元素的大小(使用大约"),但这很麻烦.
Is there any possibility in Catch C++ Unit test framework to compare std::vectors that are floating point type based? I know that I can compare size of both containers and each element (using Approx) but this is messy.
整数类型vector的比较正常工作.
Comparison of integral types vector works properly.
现在,我必须使用这种构造
Now, I must use such construction
REQUIRE(computed.size() == expected.size());
for (size_t i = 0; i < computed.size(); ++i)
REQUIRE(computed[i] == Approx(expected[i]));
但是我想使用一种衬板(它适用于整数类型):
But I would like to use one liner (it works for integral types):
REQUIRE(computed == expected);
推荐答案
您可以编写
CHECK_THAT(actual, EqualsApprox(expected));
使用此自定义匹配器:
#include <vector>
#include <functional>
#include <catch.hpp>
template<typename T, typename Compare>
struct CompareMatcher
: Catch::Matchers::Impl::MatcherBase<std::vector<T>, std::vector<T> > {
CompareMatcher(const std::vector<T> &comparator, const Compare &compare)
: m_comparator(comparator),
m_compare(compare) {}
bool match(const std::vector<T> &v) const CATCH_OVERRIDE {
if (m_comparator.size() != v.size()) {
return false;
}
for (size_t i = 0; i < v.size(); ++i) {
if (!m_compare(m_comparator[i], v[i])) {
return false;
}
}
return true;
}
virtual std::string describe() const CATCH_OVERRIDE {
return "Equals: " + Catch::toString(m_comparator);
}
const std::vector<T> &m_comparator;
Compare const &m_compare;
};
template<typename T, typename C>
CompareMatcher<T, C>
Compare(const std::vector<T> &comparator, const C &compare) {
return CompareMatcher<T, C>(comparator, compare);
}
auto EqualsApprox(const std::vector<double> &comparator) {
return Compare(comparator, [=](double actual, double expected) {
return actual == Approx(expected);
});
}
TEST_CASE("example", "[]") {
SECTION("passes") {
std::vector<double> actual {0, 1.00001};
std::vector<double> expected {0, 1};
CHECK_THAT(actual, EqualsApprox(expected));
}
SECTION("fails") {
std::vector<double> actual {0, 1.0001};
std::vector<double> expected {0, 1};
CHECK_THAT(actual, EqualsApprox(expected));
}
}
这篇关于使用C ++ Catch测试浮点std :: vector的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文