gtest - testing template class

偶尔善良 提交于 2019-12-04 19:31:38

问题


I want to test a template class with gtest. I read about TYPED_TESTs in Google Test manual and looked at official example they reference, but still can't wrap my head around getting an object of template class instantiated in my test.

Suppose the following simple template class:

template <typename T>
class Foo
{
public:
    T data ;
};

In testing class we declare

typedef ::testing::Types<int, float> MyTypes ;

Now how can I instantiate an object of class Foo for Ts listed in MyTypes in a test? E.g.

TYPED_TEST(TestFoo, test1)
{
    Foo<T> object ;
    object.data = 1.0 ;

    ASSERT_FLOAT_EQ(object.data, 1.0) ;
}

回答1:


Inside a test, refer to the special name TypeParam to get the type parameter. So you could do

TYPED_TEST(TestFoo, test1)
{
    Foo<TypeParam> object ; // not Foo<T>
    object.data = 1.0 ;

    ASSERT_FLOAT_EQ(object.data, 1.0) ;
}


来源:https://stackoverflow.com/questions/17079702/gtest-testing-template-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!