Search code examples
c++unit-testingtestcase

Can we pass parameters to the test cases functions in C++ using CppUnit?


I am using cppunit for testing my c++ code. I have written my test fixture like this

class MainTestFixture : public TestFixture
{
    CPPUNIT_TEST_SUITE(MainTestFixture);    
    CPPUNIT_TEST(Addition);
    CPPUNIT_TEST(Multiply);
    CPPUNIT_TEST_SUITE_END();

public: 
    void setUp(void);
    void tearDown(void);
protected:
    // Test Functions 
    void Addition(void);
    void Multiply(void);
};

Now if I implement test cases like

void MainTestFixture::Addition()
{
    // CPPUNIT_ASSERT(condition);
}
void MainTestFixture::Multiply()
{
    // CPPUNIT_ASSERT(condition);
}

In the above code, is it possible that I pass parameters to Addition and Multiply functions?

Where as I have made a suite for running this fixture like below

#include "MainTestFixture.h"

CPPUNIT_TEST_SUITE_REGISTRATION(MainTestFixture);

using namespace CPPUNIT_NS;
int main()
{
    // informs test-listener about testresults
    CPPUNIT_NS::TestResult testresult;

    // register listener for collecting the test-results
    CPPUNIT_NS::TestResultCollector collectedresults;
    testresult.addListener (&collectedresults);

    // register listener for per-test progress output
    CPPUNIT_NS::BriefTestProgressListener progress;
    testresult.addListener (&progress);

    // insert test-suite at test-runner by registry
    CPPUNIT_NS::TestRunner testrunner;
    testrunner.addTest (CPPUNIT_NS::TestFactoryRegistry::getRegistry().makeTest ());
    testrunner.run(testresult);

    // output results in compiler-format
    CPPUNIT_NS::CompilerOutputter compileroutputter(&collectedresults, std::cerr);
    compileroutputter.write ();

    // Output XML for Jenkins CPPunit plugin
    ofstream xmlFileOut("cppMainUnitTest.xml");
    XmlOutputter xmlOut(&collectedresults, xmlFileOut);
    xmlOut.write();

    // return 0 if tests were successful
    return collectedresults.wasSuccessful() ? 0 : 1;
}

Solution

  • No, you can not. Addition() is callback which will be registered in CPPUNIT engine and called by the driver - therefore it should use void(void) interface. Instead you could define your parameters as MainTestFixture's members.

    class MainTestFixture : public TestFixture
    {
        CPPUNIT_TEST_SUITE(MainTestFixture);    
        CPPUNIT_TEST(Addition);
        CPPUNIT_TEST(Multiply);
        CPPUNIT_TEST_SUITE_END();
    
    public: 
        void setUp(void);
        void tearDown(void);
    protected:
        // Test Functions 
        void init_fixture();
        void Addition(void);
        void Multiply(void);
    protected: 
        //data members
        param1_t m_param1;
        param2_t m_param2;
    
    };
    
    void MainTestFixture::init_fixture()
    {
         m_param1 = ...;
         m_param2 = ...;
    }
    void MainTestFixture::Addition()
    {
        param1_t res= m_param1 + ...;
        // CPPUNIT_ASSERT(condition);
    }