为Google测试装置指定构造函数参数 [英] Specify constructor arguments for a Google test Fixture
问题描述
对于Google测试,我想指定一个测试夹具,以用于不同的测试案例。
固定装置应分配和取消分配 TheClass
类及其数据管理类 TheClassData
的对象,其中数据管理类需要一个数据文件的名称。
对于不同的测试,文件名应该有所不同。
With Google test I want to specify a Test fixture for use in different test cases.
The fixture shall allocate and deallocate objects of the class TheClass
and its data management class TheClassData
, where the data management class requires the name of a datafile.
For the different tests, the file name should vary.
我定义了以下夹具: / p>
I defined the following Fixture:
class TheClassTest : public ::testing::Test {
protected:
TheClassTest(std::string filename) : datafile(filename) {}
virtual ~TheClassTest() {}
virtual void SetUp() {
data = new TheClassData(datafile);
tc = new TheClass(data);
}
virtual void TearDown() {
delete tc;
delete data;
}
std::string datafile;
TheClassData* data;
TheClass* tc;
};
现在,不同的测试应使用具有不同文件名的灯具。
想象一下,这是建立测试环境。
Now, different tests should use the fixture with different file names. Imagine this as setting up a test environment.
问题:如何从测试中指定文件名,即如何调用夹具的非默认构造函数?
The question: How can I specify the filename from a test, i.e. how to call a non-default constructor of a fixture?
我发现类似 :: testing :: TestWithParam< T>
和 TEST_P
都无济于事,因为我不想使用不同的值运行一项测试,而是使用一种夹具来运行不同的测试。
I found things like ::testing::TestWithParam<T>
and TEST_P
, which doesn't help, as I don't want to run one test with different values, but different tests with one fixture.
推荐答案
如另一个用户所建议,您无法通过使用非默认构造函数实例化夹具来实现所需的
。但是,
还有其他方法。只需重载 SetUp
函数,然后
在测试中显式调用该版本:
As suggested by another user, you cannot achieve what you want
by instantiating a fixture using a non-default constructor. However,
there are other ways. Simply overload the SetUp
function and
call that version explicitly in the tests:
class TheClassTest : public ::testing::Test {
protected:
TheClassTest() {}
virtual ~TheClassTest() {}
void SetUp(const std::string &filename) {
data = new TheClassData(filename);
tc = new TheClass(data);
}
virtual void TearDown() {
delete tc;
delete data;
}
TheClassData* data;
TheClass* tc;
};
现在在测试中只需使用此重载来设置文件名:
Now in the test simply use this overload to set up filename:
TEST_F(TheClassTest, MyTestCaseName)
{
SetUp("my_filename_for_this_test_case");
...
}
无参数将在
测试完成时自动清理。
The parameterless TearDown
will automatically clean up when
the test is complete.
这篇关于为Google测试装置指定构造函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!