Search code examples
c++cppunit

CppUnit test core dumped despite successful test. Why?


So I wanted to try TDD and set up CppUnit as test environment. I read the cookbook as I want to start small. I simply want to test a public factorial function of a class Factor. My test runs successfully but then the program suddenly core dumps and I have no idea why. I'm using g++ on Ubuntu 18.04 64-bit and CppUnit 1.14.

testmain.cpp

#include "test1.h"

int main(){

    CppUnit::TestCaller <Test1> test ("test", &Test1::testFactorial );

    CppUnit::TestSuite suite;
    suite.addTest(&test);

    CppUnit::TextUi::TestRunner runner;
    runner.addTest(&suite);
    runner.run( );
    return 0;
}

test1.h

#ifndef TEST1_H
#define TEST1_H

#include <cppunit/TestAssert.h>
#include <cppunit/TestCase.h>
#include <cppunit/TestFixture.h>
#include <cppunit/TestCaller.h>
#include <cppunit/TestResult.h>
#include <cppunit/ui/text/TestRunner.h>
#include <cppunit/TestSuite.h>

#include "factorial.h"

class Test1 : public CppUnit::TestFixture {
private:
    Factor *f_6;

public:
    void setUp(){
        f_6 = new Factor();
    }

    void tearDown(){
        //to see whether my variable gets freed
        std::cout << "delete testvariable\n";
        delete f_6;
    }

    void testFactorial(){
        int f6 = f_6->factorial(6);
        CPPUNIT_ASSERT(f6 == 720);
    }
};

#endif

factorial.h

#ifndef FACTORIAL_H
#define FACTORIAL_H

class Factor{

public:
    int factorial(int arg){
        int result = 1;
        for(int i = 1; i <= arg; i++){
            result *= i;
        }
        return result;
    }

};

#endif

Commandline Output:

user@computer:~/folder$ make test
g++ -g -Wall -o testexecutable testmain.cpp -lcppunit
user@computer:~/folder$ ./testexecutable 
.delete testvariable



OK (1 tests)


free(): invalid size
Aborted (core dumped)
user@computer:~/folder$

Why is there this weird free and core dump in the execution of the test case?


Solution

  • CppUnit test suites delete all the test objects in the destructor. So you need to allocate a test in your main, rather than using one directly on the stack.

    Similarly I think a TestRunner also does a cleanup so you need to allocate the TestSuide object too.

    See the "Suite" and "TestRunner" headings in: http://cppunit.sourceforge.net/doc/cvs/cppunit_cookbook.html

    Therefore your main becomes:

    int main() {
        CppUnit::TestSuite* suite = new CppUnit::TestSuite();
        suite->addTest(new CppUnit::TestCaller<Test1>("test", &Test1::testFactorial));
        CppUnit::TextUi::TestRunner runner;
        runner.addTest(suite);
        runner.run();
        return 0;
    }