9

Catch C++ 单元测试框架中是否有可能比较基于浮点类型的 std::vectors?我知道我可以比较两个容器和每个元素的大小(使用 Approx),但这很混乱。

整数类型向量的比较工作正常。

现在,我必须使用这样的结构

REQUIRE(computed.size() == expected.size());
for (size_t i = 0; i < computed.size(); ++i)
    REQUIRE(computed[i] == Approx(expected[i]));

但我想使用一个班轮(它适用于整数类型):

REQUIRE(computed == expected);
4

3 回答 3

6

下面的结构由 Catch2 本身提供。无需自己动手。

 REQUIRE_THAT( computed, Catch::Approx(expected).epsilon(1.e-5) );
于 2019-09-02T08:46:57.763 回答
5

你可以写

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));
    }
}
于 2017-10-25T11:20:26.533 回答
1

我有同样的需求,我决定使用简单的宏:

#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])); \
            } \
    }

该宏可用作单行,每次成功比较仅计为一个断言。

于 2018-07-30T15:47:24.677 回答