问题描述
gtest中的参数化测试可让您使用不同的参数测试代码,而无需编写同一测试的多个副本。seen here
我看到了传递值的示例,例如std :: pair,std :: tuple等。
但是我不确定如何将数组/ initializer_list传递到测试中。
预期如下:
$ sudo apt install nodejs
Reading package lists... Done
Building dependency tree
Reading state @R_200_4045@ion... Done
The following packages will be upgraded:
nodejs
1 upgraded,0 newly installed,0 to remove and 38 not upgraded.
Need to get 24.7 MB of archives.
After this operation,111 kB of additional disk space will be used.
Get:1 https://deb.nodesource.com/node_14.x focal/main amd64 nodejs amd64 14.8.0-deb-1nodesource1 [24.7 MB]
Fetched 24.7 MB in 20s (1,246 kB/s)
(Reading database ... 155976 files and directories currently installed.)
Preparing to unpack .../nodejs_14.8.0-deb-1nodesource1_amd64.deb ...
Unpacking nodejs (14.8.0-deb-1nodesource1) over (14.7.0-deb-1nodesource1) ...
Setting up nodejs (14.8.0-deb-1nodesource1) ...
Processing triggers for man-db (2.9.1-1) ...
$ nodejs -v
Command 'nodejs' not found,but can be installed with:
sudo apt install nodejs
有可能吗?如果是,怎么办?
解决方法
您可以传递任何想要的类型作为参数。当您从类模板WithParamInterface
(或TestWithParam
)继承测试夹具a时,可以提供参数类型:
class FooTest: public TestWithParam<std::array<int,3>>
//class FooTest: public TestWithParam<std::vector<int>>
//class FooTest: public TestWithParam<std::initializer_list<int>> //I'm not sure if this is a good idea,initializer_list has weird lifetime management
{};
INSTANTIATE_TEST_SUITE_P(Sample,FooTest,testing::Values(std::array<int,3>{1,23,53},std::array<int,3>{534,34,456});
See it online。
您不能使用裸括号初始化列表并让编译器推断类型,因为::testing::Values()
接受模板参数,并且编译器不知道该模板参数应变为哪种类型。
假设我们有class BarTest: public TestWithParam<std::string>
。对于::testing::Values
,我们可以传递实际的std :: string对象::testing::Values(std::string{"asdf"},"qwer"s)
或隐式可转换为std :: string的对象,例如字符串文字:::testing::Values("zxcv")
。后者将推断出类型为const char*
,而实际的std :: string在GoogleTest代码中更深入地构造。