Catch2 - Populating singleton with different mock data for different test files

1.5k views Asked by At

I am using Catch2 for unit testing in my C++ project. I have a singleton class and it is being used in different test files. For example one file might be testing the singleton itself, and another file testing the interaction between the singleton and another component. 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.

To my knowledge, there seems to be two ways I can go about.

  1. Using Test Cases and Sections

TestA.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

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.

  1. Use of 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.

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?

1

There are 1 answers

0
arved On BEST ANSWER

You probably want a Fixture.

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