我们可以使用CppUnit将参数传递给C ++中的测试用例函数吗?

时间:2015-09-04 09:21:14

标签: c++ unit-testing testcase

我正在使用cppunit来测试我的c ++代码。我已经写了这样的测试夹具

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);
};

现在,如果我实现像

这样的测试用例
void MainTestFixture::Addition()
{
    // CPPUNIT_ASSERT(condition);
}
void MainTestFixture::Multiply()
{
    // CPPUNIT_ASSERT(condition);
}

在上面的代码中,我是否可以将参数传递给加法和乘法函数?

我已经制作了一个套件来运行这个夹具,如下所示

#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;
}

1 个答案:

答案 0 :(得分:0)

不,你不能。 Addition()是回调,它将在CPPUNIT引擎中注册并由驱动程序调用 - 因此它应该使用void(void)接口。相反,您可以将参数定义为MainTestFixture的成员。

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);
}