如何在 Google 测试中使用不同模板测试多个模板化类的相同行为?

How to test the same behaviour for multiple templated classes with different templates in Google Test?

本文关键字:测试 Google      更新时间:2023-10-16

我正在C++ 17中练习排序算法,并按如下方式实现了我的单元测试(以下编译和所有测试均为绿色):

template <typename T>
class SortingmethodTest : public ::testing::Test
{
protected:   
T sortingmethod;
static constexpr int amount_test_data[7] = {0, 4, 8, 10, 256, 1000, 1234};
};
using sortingmethods = ::testing::Types<STLSort<int>,
InsertionSort<int>,
ShellSort<int>,
MergeSort<int>,
OptimizedMergeSort<int>,
QuickSort<int>>;
TYPED_TEST_SUITE(SortingmethodTest, sortingmethods);
TYPED_TEST(SortingmethodTest, sort)
{
for (const auto& amount : this->amount_test_data)
{
Sortvector<int> test(amount);
test.vul_random_zonder_dubbels(); // Fills the vector
this->sortingmethod(test); // operator() of the sortmethod used (STLSort, InsertionSort, ...) sorts the vector
ASSERT_TRUE(test.is_range());
ASSERT_TRUE(test.is_gesorteerd());
ASSERT_TRUE(std::is_sorted(test.begin(), test.end()));
}
}
TYPED_TEST(SortingmethodTest, sort_reverse)
{
// ...
}
TYPED_TEST(SortingmethodTest, sort_already_sorted)
{
// ...
}
TYPED_TEST(SortingmethodTest, sort_empty)
{
// ...
}

我想对除整数以外的其他类型的重复相同的测试,例如

STLSort<int>,
InsertionSort<int>,
ShellSort<int>,
MergeSort<int>,
OptimizedMergeSort<int>,
QuickSort<int>
STLSort<double>,
InsertionSort<double>,
ShellSort<double>,
MergeSort<double>,
OptimizedMergeSort<double>,
QuickSort<double>
STLSort<CustomType>,
InsertionSort<CustomType>,
ShellSort<CustomType>,
MergeSort<CustomType>,
OptimizedMergeSort<CustomType>,
QuickSort<CustomType>
...

如何在谷歌测试C++中尽可能干净地并尽可能多地重用?我迷失在类型化测试和类型参数化测试 [1] 的丛林中:什么时候应该使用其中之一?

带着亲切的问候,

[1] https://github.com/google/googletest/blob/master/docs/advanced.md#type-parameterized-tests

到目前为止,googletest API 并没有为我们提供更多的 利用现代C++使测试代码简洁,特别是对于测试 模板。但直到 v1.8.x(当前发布系列在 这个日期)GoogleTest一直致力于C++98兼容性,这在很大程度上就是原因。 即将发布的1.9.x版本将继续与C++11兼容,我们希望 以获得更强大的 API。

尽管如此,现在还是可以编写相当简洁明了的googletest代码 做你想做的事情:也就是说,对只有一个不同值的全等模板进行单元测试 模板参数。

方法不止一种。这是其中之一的工作示例, 使用类型参数化测试。

我们将有一组三个模板

template<typename T> struct (AA|BB|CC) {...};

每个都提供(至少)接口:

Name::Name(T const & u);
Name::operator int() const;
Name Name::operator+(Name const & u) const;
Name & Name::operator+=(Name const & u);
Name Name::operator-(Name const & u) const;
Name & Name::operator-=(Name const & u);

对于Name=(AA|BB|CC).我们想要 对这个接口进行单元测试,对于每个接口(AA|BB|CC),每个实例化 六种类型中的每一种:

char, int, float, AA<char>, BB<int>, CC<float>

因此,这是要测试的 18 个实例:

AA<char>, AA<int>, AA<float>, AA<AA<char>>, AA<BB<int>>, AA<CC<float>>
BB<char>, BB<int>, BB<float>, BB<AA<char>>, BB<BB<int>>, BB<CC<float>>
CC<char>, CC<int>, CC<float>, CC<AA<char>>, CC<BB<int>>, CC<CC<float>>

为了简短起见,我们将只实现两个通用测试。对于对象abc任何实例化的测试类型:

  • a = b + c; b += c后,a == b.
  • 给定b != c,在a = b - c; c -= b之后,则a != c

(至少,只要操作不溢出或 失去精度,我会避免)。

因此,我们期望看到总共进行36项测试。

对于这个插图,我不在乎AABBCC是什么,除了它们的共同界面, 所以我只是从单个模型中以相同的方式推导出它们,如下所示:

some_types.h

#pragma once
#include <type_traits>
namespace detail {
template<typename T>
struct bottom_type {
using type = T;
};
template<template<typename ...> class C, typename ...Ts>
struct bottom_type<C<Ts...>> {
using type = typename C<Ts...>::type;
};
}
template<typename T>
using bottom_t = typename detail::bottom_type<T>::type;
template<
typename T,
typename Enable = std::enable_if_t<std::is_arithmetic_v<bottom_t<T>>>
>
struct model
{
using type = bottom_t<T>;
model() = default;
model(model const &) = default;
model(T const & t)
: _t{t}{}
operator type() const { return _t; }
auto operator+(model const & u) const {
return _t + u;
}
auto & operator+=(model const & u) {
_t += u;
return *this;
}
auto operator-(model const & u ) const {
return _t - u;
}
auto & operator-=(model const & u ) {
_t -= u;
return *this;
}
protected:
type _t = 0;
};
template<typename T> struct AA : model<T>{ using model<T>::model; };
template<typename T> struct BB : model<T>{ using model<T>::model; };
template<typename T> struct CC : model<T>{ using model<T>::model; };

现在这是我的谷歌测试代码:

主.cpp

#include <array>
#include <algorithm>
#include <random>
#include <type_traits>
#include <limits>
#include <gtest/gtest.h>
#include "some_types.h"
template<typename T>
struct fixture : public ::testing::Test
{
protected:
template<typename U>
static auto const & test_data() {
using type = bottom_t<U>;
static std::array<type,1000> data;
static bool called;
if (!called) {
std::default_random_engine gen;
auto low = std::numeric_limits<type>::min() / 2;
auto high = std::numeric_limits<type>::max() / 2;
auto dist = [&low,&high](){
if constexpr (std::is_floating_point_v<type>) {
return std::uniform_real_distribution<type>(low,high);
} else {
return std::uniform_int_distribution<type>(low,high);
}
}();
std::generate(
data.begin(),data.end(),[&dist,&gen](){ return dist(gen); });
called = true;
}
return data;
}
};

template<template<typename> class C, typename ...Ts>
using test_types = ::testing::Types<C<Ts>...>;
using AA_test_types = test_types<AA,char,int,float,AA<char>,BB<int>,CC<float>>;
using BB_test_types = test_types<BB,char,int,float,AA<char>,BB<int>,CC<float>>;
using CC_test_types = test_types<CC,char,int,float,AA<char>,BB<int>,CC<float>>;
TYPED_TEST_SUITE_P(fixture);
TYPED_TEST_P(fixture, addition)
{
using wrapped_type = typename TypeParam::type;
auto const & data = this->template test_data<wrapped_type>();
auto fi = data.begin(); auto ri = data.rbegin();
for ( ; fi != ri.base(); ++fi, ++ri)
{
TypeParam lhs{*fi}, rhs{*ri};
auto sum = lhs + rhs;
lhs += rhs;
ASSERT_EQ(lhs,sum);
}
}
TYPED_TEST_P(fixture, subtraction)
{
using wrapped_type = typename TypeParam::type;
auto const & data = this->template test_data<wrapped_type>();
auto fi = data.begin(); auto ri = data.rbegin();
for ( ; fi != ri.base(); ++fi, ++ri) {
TypeParam lhs{*fi}, rhs{*ri};
if (lhs != rhs) {
auto diff = lhs - rhs;
rhs -= lhs;
ASSERT_NE(rhs,diff);
}
}
}
REGISTER_TYPED_TEST_SUITE_P(fixture,addition,subtraction);
INSTANTIATE_TYPED_TEST_SUITE_P(AA_tests, fixture, AA_test_types);
INSTANTIATE_TYPED_TEST_SUITE_P(BB_tests, fixture, BB_test_types);
INSTANTIATE_TYPED_TEST_SUITE_P(CC_tests, fixture, CC_test_types);
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

让我们来看看兴趣点:-

template<template<typename> class C, typename ...Ts>
using test_types = ::testing::Types<C<Ts>...>;

在这里,我正在test_types::testing::Types<SomeType...>列表的模板别名 其中SomeType将是受测模板之一的实例化。因为它 碰巧,我的模板AABBCC(像你的)都是形式:

template<typename T> class;

所以我希望test_types成为:

::testing::Types<C<Ts>...>

然后我定义 3 个具体的类型别名:

using AA_test_types = test_types<AA,char,int,float,AA<char>,BB<int>,CC<float>>;
using BB_test_types = test_types<BB,char,int,float,AA<char>,BB<int>,CC<float>>;
using CC_test_types = test_types<CC,char,int,float,AA<char>,BB<int>,CC<float>>;

分别相当于:

::testing::Types<AA<char>, AA<int>, AA<float>, AA<AA<char>>, AA<BB<int>>, AA<CC<float>>>;
::testing::Types<BB<char>, BB<int>, BB<float>, BB<AA<char>>, BB<BB<int>>, BB<CC<float>>>;
::testing::Types<CC<char>, CC<int>, CC<float>, CC<AA<char>>, CC<BB<int>>, CC<CC<float>>>;

然后,我使用模板夹具fixture定义一个类型参数化的测试套件。

TYPED_TEST_SUITE_P(fixture);

然后,我定义两个类型参数化的测试模式。

TYPED_TEST_P(fixture, addition)
{
using wrapped_type = typename TypeParam::type;
auto const & data = this->template test_data<wrapped_type>();
auto fi = data.begin(); auto ri = data.rbegin();
for ( ; fi != ri.base(); ++fi, ++ri)
{
TypeParam lhs{*fi}, rhs{*ri};
auto sum = lhs + rhs;
lhs += rhs;
ASSERT_EQ(lhs,sum);
}
}
TYPED_TEST_P(fixture, subtraction)
{
using wrapped_type = typename TypeParam::type;
auto const & data = this->template test_data<wrapped_type>();
auto fi = data.begin(); auto ri = data.rbegin();
for ( ; fi != ri.base(); ++fi, ++ri) {
TypeParam lhs{*fi}, rhs{*ri};
if (lhs != rhs) {
auto diff = lhs - rhs;
rhs -= lhs;
ASSERT_NE(rhs,diff);
}
}
}

然后,我注册这两种模式,以便在每次实例化时进行实例化fixture

REGISTER_TYPED_TEST_SUITE_P(fixture,addition,subtraction);

然后我fixture(AA|BB|CC)_tests为 测试类型列表分别(AA|BB|CC)_test_types

INSTANTIATE_TYPED_TEST_SUITE_P(AA_tests, fixture, AA_test_types);
INSTANTIATE_TYPED_TEST_SUITE_P(BB_tests, fixture, BB_test_types);
INSTANTIATE_TYPED_TEST_SUITE_P(CC_tests, fixture, CC_test_types);

仅此而已。编译和链接:

$ g++ -std=c++17 -Wall -Wextra -pedantic -o gtester main.cpp -lgtest -pthread

跑:

./gtester
[==========] Running 36 tests from 18 test suites.
[----------] Global test environment set-up.
[----------] 2 tests from AA_tests/fixture/0, where TypeParam = AA<char>
[ RUN      ] AA_tests/fixture/0.addition
[       OK ] AA_tests/fixture/0.addition (0 ms)
[ RUN      ] AA_tests/fixture/0.subtraction
[       OK ] AA_tests/fixture/0.subtraction (1 ms)
[----------] 2 tests from AA_tests/fixture/0 (1 ms total)
[----------] 2 tests from AA_tests/fixture/1, where TypeParam = AA<int>
[ RUN      ] AA_tests/fixture/1.addition
[       OK ] AA_tests/fixture/1.addition (0 ms)
[ RUN      ] AA_tests/fixture/1.subtraction
[       OK ] AA_tests/fixture/1.subtraction (0 ms)
[----------] 2 tests from AA_tests/fixture/1 (0 ms total)
...
...
...
[----------] 2 tests from CC_tests/fixture/4, where TypeParam = CC<BB<int> >
[ RUN      ] CC_tests/fixture/4.addition
[       OK ] CC_tests/fixture/4.addition (0 ms)
[ RUN      ] CC_tests/fixture/4.subtraction
[       OK ] CC_tests/fixture/4.subtraction (0 ms)
[----------] 2 tests from CC_tests/fixture/4 (0 ms total)
[----------] 2 tests from CC_tests/fixture/5, where TypeParam = CC<CC<float> >
[ RUN      ] CC_tests/fixture/5.addition
[       OK ] CC_tests/fixture/5.addition (0 ms)
[ RUN      ] CC_tests/fixture/5.subtraction
[       OK ] CC_tests/fixture/5.subtraction (0 ms)
[----------] 2 tests from CC_tests/fixture/5 (0 ms total)
[----------] Global test environment tear-down
[==========] 36 tests from 18 test suites ran. (4 ms total)
[  PASSED  ] 36 tests.