How to test c++ template class with multiple template parameters using gtest?

牧云@^-^@ 提交于 2019-11-29 02:14:46

A trick would be to make gtest see a single type parameter, with nested types. To do this, you can define a templated structure such as:

template <typename A, typename B>
struct TypeDefinitions
{
  typedef typename A MyA;
  typedef typename B MyB;
};

Which you can pass to your typed-test fixture:

template <class T>
class QueueTestNew : public testing::Test
{
protected:
  QueueTestNew() : queue(CreateQueue<typename T::MyA, typename T::MyB>()){}
  virtual ~QueueTestNew(){ delete queue; }
  QueueNew<typename T::MyA, typename T::MyB>* const queue;
};

// The list of types we want to test.
typedef ::testing::Types <TypeDefinitions<char,char>,
                          TypeDefinitions<int,int> > Implementations;

TYPED_TEST_CASE(QueueTestNew, Implementations);

TYPED_TEST(QueueTestNew, DefaultConstructor)
{
  typename TypeParam::MyA someA; // if you need access to the subtypes in the test itself

  EXPECT_EQ(123u, this->queue->size());
}

An example that might also work, and doesn't require a custom struct, is using std::tuples

template <class T>
class TestThreeParams : public testing::Test {};

typedef ::testing::Types <std::tuple<float64_t, float32_t, int16>, std::tuple<int64, int8, float32_t> > Implementations;

TYPED_TEST_CASE(TestThreeParams, Implementations);

TYPED_TEST(TestThreeParams, MaximumTest)
{
    using A = std::tuple_element<0, decltype(TypeParam())>::type;
    using B = std::tuple_element<1, decltype(TypeParam())>::type;
    using C = std::tuple_element<2, decltype(TypeParam())>::type;

    bool test = (Max<A, B, C>(A(-5), B(2), C(5)) == 5);
    EXPECT_TRUE(test);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!