简体   繁体   English

Catch2 - 使用不同测试文件的不同模拟数据填充 singleton

[英]Catch2 - Populating singleton with different mock data for different test files

I am using Catch2 for unit testing in my C++ project.我在我的 C++ 项目中使用 Catch2 进行单元测试。 I have a singleton class and it is being used in different test files.我有一个 singleton class,它被用于不同的测试文件。 For example one file might be testing the singleton itself, and another file testing the interaction between the singleton and another component.例如,一个文件可能正在测试 singleton 本身,而另一个文件可能正在测试 singleton 与另一个组件之间的交互。 As such, I was wondering if there is a way that I can populate the singleton class with different sets of mock data for each test file.因此,我想知道是否有一种方法可以为每个测试文件使用不同的模拟数据集填充 singleton class。

To my knowledge, there seems to be two ways I can go about.据我所知,似乎有两种方法可以让我 go 一下。

  1. Using Test Cases and Sections使用测试用例和部分

TestA.cpp测试A.cpp

TEST_CASE("A") {
    SingletonClass& sc = SingletonClass::getInstance();
    sc.clear();
    sc.add(data1);
    sc.add(data2);
    // ... more methods to populate singletonClass
  
    SECTION("Check A1"){
        // Perform test checks
    }

    SECTION("Check A2"){
        // Perform test checks
    }
}

TestB.cpp测试B.cpp

TEST_CASE("B") {
    SingletonClass& sc = SingletonClass::getInstance();
    sc.clear();
    sc.add(data3);    // Different data from TestA.cpp
    sc.add(data4);
    // ... more methods to populate singletonClass
  
    SECTION("Check B1"){
        // Perform test checks
    }

    SECTION("Check B2"){
        // Perform test checks
    }
}

However this means that the setup functions will be run twice in each test file, which is not necessary and it is something I hope to avoid.然而,这意味着设置函数将在每个测试文件中运行两次,这是没有必要的,也是我希望避免的事情。 Neither do I want to lump all my tests under one SECTION/TEST_CASE.我也不想将所有测试集中在一个 SECTION/TEST_CASE 下。

  1. Use of Listeners Listeners的使用

I understand I can create and register my own Listener class and override the testCaseStarting and testCaseEnded methods and this seems to apply for all TEST_CASE, but I want to have different setups for TestA and TestB.我知道我可以创建和注册我自己的Listener class 并覆盖testCaseStartingtestCaseEnded方法,这似乎适用于所有 TEST_CASE,但我想对 TestA 和 TestB 进行不同的设置。

Hence is there a better way I can setup my singleton class differently in each test files such that it is similar to running a setup and teardown function at the beginning and at the end in each test file?因此,有没有更好的方法可以在每个测试文件中以不同方式设置我的 singleton class,这样它类似于在每个测试文件的开头和结尾运行设置和拆卸 function?

You probably want a Fixture.你可能想要一个夹具。

Fixture documentation: https://github.com/catchorg/Catch2/blob/master/docs/test-fixtures.md夹具文档: https://github.com/catchorg/Catch2/blob/master/docs/test-fixtures.md

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM