Parameterizing a test using CppUnit

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

    Based on consumerwhore answer, I ended up with a very nice approach where I can create multiple tests using a one-line registration macro with as many parameters I want.

    Just define a parameter class:

    class Param
    {
    public:
        Param( int param1, std::string param2 ) :
            m_param1( param1 ),
            m_param2( param2 )
        {
        }
    
        int m_param1;
        std::string m_param2;
    };
    

    Make your test fixture use it as "non-type template parameter" (I think that's how it's called):

    template 
    class my_test : public CPPUNIT_NS::TestFixture
    {
        CPPUNIT_TEST_SUITE(my_test);
        CPPUNIT_TEST( doProcessingTest );
        CPPUNIT_TEST_SUITE_END();
    
        void doProcessingTest()
        {
            std::cout << "Testing with " << T.m_param1 << " and " << T.m_param2 << std::endl;
        };
    };
    

    Have a small macro creating a parameter and registering a new test fixture:

    #define REGISTER_TEST_WITH_PARAMS( name, param1, param2 ) \
        Param name( param1, param2 ); \
        CPPUNIT_TEST_SUITE_REGISTRATION(my_test);
    

    Finally, add as many tests you want like that:

    REGISTER_TEST_WITH_PARAMS( test1, 1, "foo" );
    REGISTER_TEST_WITH_PARAMS( test2, 3, "bar" );
    

    Executing this test will give you:

    my_test::doProcessingTestTesting with 1 and foo : OK
    my_test::doProcessingTestTesting with 3 and bar : OK
    OK (2)
    Test completed, after 0 second(s). Press enter to exit
    

提交回复
热议问题