WritingTests tutorial file

This tutorial is not automatically generated from a file.

In this tutorial we show how to write a test using CxxTest.

The following header file need to be included.

#include <cxxtest/TestSuite.h>

Now we have to define a class containing the tests. It is sensible to name the class the same name as the filename. The class should inherit from CxxTest::TestSuite.

class TestWritingTestsTutorial : public CxxTest::TestSuite
{

Now we can define some tests, which must be public, begin with the word 'Test' return void, and take in no parameters.

public:
    void TestOnePlusOneEqualsTwo()
    {

To test two integers are equal, we can use the macro TS_ASSERT_EQUALS.

        int some_number = 1+1;
        TS_ASSERT_EQUALS(some_number, 2);

To test whether two numbers are equal to within a certain (absolute) tolerance we can use TS_ASSERT_DELTA. This should almost always be used when comparing two doubles.

        double another_number = 1.000001+1.0001;
        TS_ASSERT_DELTA(another_number, 2.0, 1e-2);
    }

This second test shows some of the other TS_ASSERT macros that are available.

    void TestSomeOtherStuff()
    {
        TS_ASSERT( 1==1 ); // however, it is better to use TS_ASSERT_EQUALS, below
        TS_ASSERT_EQUALS( (true||false), true);
        TS_ASSERT_DIFFERS( 1.348329534564385643543957436, 1.348329534564395643543957436);
        TS_ASSERT_LESS_THAN(2.71828183, 3.14159265); // Note: to test if y is greater than x, use TS_ASSERT_LESS_THAN(y,x).
        TS_ASSERT_LESS_THAN_EQUALS(-1e100, 1e100);
        TS_ASSERT_THROWS_ANYTHING( throw 0; ); // normally you would put a function call inside the brackets

        double x;
        TS_ASSERT_THROWS_NOTHING( x=1; );  // normally you would put a function call inside the brackets
    }
};

Note that methods which don't start with 'Test' are compiled but not run. So, if you want to stop a single test running, just put an 'x' or a 'don't' before its name

    void dontTestThis()
    {
        TS_ASSERT_EQUALS(1,2);
    }

Code

The full code is given below

#include <cxxtest/TestSuite.h>

class TestWritingTestsTutorial : public CxxTest::TestSuite
{
public:
    void TestOnePlusOneEqualsTwo()
    {
        int some_number = 1+1;
        TS_ASSERT_EQUALS(some_number, 2);
        double another_number = 1.000001+1.0001;
        TS_ASSERT_DELTA(another_number, 2.0, 1e-2);
    }

    void TestSomeOtherStuff()
    {
        TS_ASSERT( 1==1 );
        TS_ASSERT_EQUALS( (true||false), true);
        TS_ASSERT_DIFFERS( 1.348329534564385643543957436, 1.348329534564395643543957436);
        TS_ASSERT_LESS_THAN(2.71828183, 3.14159265);
        TS_ASSERT_LESS_THAN_EQUALS(-1e100, 1e100);
        TS_ASSERT_THROWS_ANYTHING( throw 0; );
    }

    void dontTestThis()
    {
        TS_ASSERT_EQUALS(1,2);
    }
};