'Generating mathematical vectors for math library unit tests

I am attempting to unit test some functions on my Vector (as in math vector) class:

template <typename T, size_t N>
struct Vector {
    std::array<T, N> data;
    ...
    constexpr inline auto magnitude2() const noexcept -> T {...}
    ...
}

I have written a type parameterized unit test for this (over both T and N) as follows (shown simplified):

TYPED_TEST(VectorTestFixture, magnitude2) {
    using T = ...;  // Get from gtest
    static constexpr auto N = ...;  // Get from gtest

    auto expected = T{};
    auto vec = Vector<T, N>{};

    for (auto i = 0u; i < N; ++i) {
        auto x = static_cast<T>(i);
        vec[i] = x;

        expected += x * x;
    }

    ASSERT_EQ(vec.magnitude2(), expected);
}

This dynamically creates a vector from incrementing integers. E.g. {0, 1, 2, 3} or {0, 1, 2}. It then compares magnitude2 on this vector to a dynamically determined expected value.

This seems counter to the idea of TDD though, as the test basically has the same logic as the code being tested. Also, it does not scale well with other operations (like add).

Potentially I could write test cases for each vector size manually, and then convert to each possible type, but that's certainly not very elegant.

I would like to avoid manually writing test cases for the different combinations of type and size. Does anyone have ideas on an approach for generating test cases here?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source