c++ - 为 Google 测试夹具指定构造函数参数

标签 c++ unit-testing constructor googletest

对于 Google 测试,我想指定一个测试夹具以用于不同的测试用例。 fixture 应分配和释放 TheClass 类的对象及其数据管理类TheClassData ,其中数据管理类需要数据文件的名称。
对于不同的测试,文件名应该不同。

我定义了以下 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;
};

现在,不同的测试应该使用具有不同文件名的夹具。 将其想象成设置测试环境。

问题:如何从测试中指定文件名,即如何调用夹具的非默认构造函数?

我发现了类似 ::testing::TestWithParam<T> 的东西和 TEST_P ,这没有用,因为我不想用不同的值运行一个测试,而是用一个夹具运行不同的测试。

最佳答案

根据另一位用户的建议,您无法实现您想要的 通过使用非默认构造函数实例化夹具。然而, 还有其他方法。只需重载 SetUp 函数,然后 在测试中显式调用该版本:

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;
};

现在在测试中简单地使用这个重载来设置文件名:

TEST_F(TheClassTest, MyTestCaseName)
{
    SetUp("my_filename_for_this_test_case");

    ...
}

无参数的TearDown会自动清理 测试完成。

关于c++ - 为 Google 测试夹具指定构造函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38207346/

相关文章:

c++ - CUnit - 'Mocking' libc 函数

java - Java中类似构造函数的语句来调用super

C++ 代码 : class or structure: difficult to understand

c# - 单元测试异步函数

c++ - 渲染对象的所有实例维护对共享纹理/资源的指针/引用的最佳方法

javascript - 有条件地运行带有或不带有 Jest 模拟的测试

c++ - 为什么我的回推功能不起作用,只是出现段错误

ios - Objective c 初始值设定项的歧义

c++ - 我的操作系统中的 mykernel.iso 执行错误

c++ - 为什么wxWidgets在调用new之后从不调用delete?