问题
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.
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);
回答1:
You can write
CHECK_THAT(actual, EqualsApprox(expected));
using this custom matcher:
#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));
}
}
回答2:
The construction below is provided by Catch2 itself. No need to roll your own.
REQUIRE_THAT( computed, Catch::Approx(expected).epsilon(1.e-5) );
回答3:
I had the same need and I decided to use the simple macro:
#define CHECK_VEC_EQUAL(x, y) \
REQUIRE(x.size() == y.size()); \
for (size_t i = 0; i < x.size(); ++i) { \
if (x[i] != Approx(y[i])) { \
REQUIRE(x[i] == Approx(y[i])); \
} \
}
This macro can be used as a one-liner and each successful comparison only counts as a single assertion.
来源:https://stackoverflow.com/questions/41160846/test-floating-point-stdvector-with-c-catch