Parameterizing a test using CppUnit

前端 未结 7 1362
情话喂你
情话喂你 2021-01-05 07:56

My organization is using CppUnit and I am trying to run the same test using different parameters. Running a loop inside the test is not a good option as any failure will abo

7条回答
  •  生来不讨喜
    2021-01-05 08:15

    This is a very old question, but I just needed to do something similar and came up with the following solution. I'm not 100% happy with it, but it seems to do the job quite well

    1. Define a set of input parameters to a testing method. For example, let's say these are strings, so let's do:

      std::vector testParameters = { "string1", "string2" };
      size_t testCounter = 0;
      
    2. Implement a generic tester function, which with each invocation will take the next parameter from the test array, e.g.:

      void Test::genericTester()
      {
        const std::string ¶m = testParameters[testCounter++];
      
        // do something with param
      } 
      
    3. In the test addTestToSuite() method declaration (hidden by the CPPUNIT macros) instead of (or next to) defining methods with the CPPUNIT_TEST macros, add code similar to this:

      CPPUNIT_TEST_SUITE(StatementTest);
      
      testCounter = 0;
      for (size_t i = 0; i < testParameters.size(); i++) {
        CPPUNIT_TEST_SUITE_ADD_TEST(
          ( new CPPUNIT_NS::TestCaller(
                    // Here we use the parameter name as the unit test name.
                    // Of course, you can make test parameters more complex, 
                    // with test names as explicit fields for example.
                    context.getTestNameFor( testParamaters[i] ),
                    // Here we point to the generic tester function.
                    &TestFixtureType::genericTester,
                    context.makeFixture() ) ) );
      }
      
      CPPUNIT_TEST_SUITE_END();
      

    This way we register genericTester() multiple times, one for each parameter, with a name specified. This seems to work for me quite well.

    Hope this helps someone.

提交回复
热议问题