Parameterizing a test using CppUnit

前端 未结 7 1360
情话喂你
情话喂你 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:37

    The following class/helper macro pair works for my current use-cases. In your TestFixture subclass, just define a method which accepts one parameter and then add the test with PARAMETERISED_TEST(method_name, argument_type, argument_value).

    #include <cppunit/extensions/HelperMacros.h>
    #include <cppunit/ui/text/TestRunner.h>
    
    template <class FixtureT, class ArgT>
    class ParameterisedTest : public CppUnit::TestCase {
    public:
      typedef void (FixtureT::*TestMethod)(ArgT);
      ParameterisedTest(std::string name, FixtureT* fix, TestMethod f, ArgT a) :
        CppUnit::TestCase(name), fixture(fix), func(f), arg(a) {
      }
      ParameterisedTest(const ParameterisedTest* other) = delete;
      ParameterisedTest& operator=(const ParameterisedTest& other) = delete;
    
      void runTest() {
        (fixture->*func)(arg);
      }
      void setUp() { 
        fixture->setUp(); 
      }
      void tearDown() { 
        fixture->tearDown(); 
      }
    private:
      FixtureT* fixture;
      TestMethod func;
      ArgT arg;
    };
    
    #define PARAMETERISED_TEST(Method, ParamT, Param)           \
      CPPUNIT_TEST_SUITE_ADD_TEST((new ParameterisedTest<TestFixtureType, ParamT>(context.getTestNameFor(#Method #Param), \
                                              context.makeFixture(), \
                                              &TestFixtureType::Method, \
                                                  Param)))
    
    class FooTests : public CppUnit::TestFixture {
      CPPUNIT_TEST_SUITE(FooTests);
      PARAMETERISED_TEST(ParamTest, int, 0);
      PARAMETERISED_TEST(ParamTest, int, 1);
      PARAMETERISED_TEST(ParamTest, int, 2);
      CPPUNIT_TEST_SUITE_END();
    public:
      void ParamTest(int i) {
        CPPUNIT_ASSERT(i > 0);
      }
    };
    CPPUNIT_TEST_SUITE_REGISTRATION(FooTests);
    
    int main( int argc, char **argv)
    {
      CppUnit::TextUi::TestRunner runner;
      CppUnit::TestFactoryRegistry &registry = CppUnit::TestFactoryRegistry::getRegistry();
      runner.addTest( registry.makeTest() );
      bool wasSuccessful = runner.run( "", false );
      return wasSuccessful;
    }
    
    0 讨论(0)
提交回复
热议问题