Unit Test Projects

Making a basic Unit Test project.


Unit Test Project Template

You can use the UnitTestProject template just like the BasicProject template.

The starter code uses a file named tests.cpp instead of main.cpp. In that file, you should probably not touch anything between the two lines that looks like these:

    //-----------------------------------

That code is what will automatically create a main function and add code to run all of your tests.

Separating Functions from Tests

To place your functions in a separate file from the unit tests, do the following:

  1. Add new .h and .cpp files to the project folder and name them something like functions.h and functions.cpp.

  2. To make sure the code gets compiled, add the .cpp file to your Makefile's SHARED_FILES list by making that line look like:

    SHARED_FILES = functions.cpp
    
  3. Include your .h file from the files with the unit tests after the last //-------------------------:

    ...
    using doctest::Approx;
    //-----------------------------------------------------------------------------------
       
    #include "functions.h"    //<------  Include your .h file
       
    TEST_CASE...
    
  4. To test your setup, add this function declaration to your .h:

    int foo();
    

    This definition to your .cpp:

    #include "functions.h"    //<------  Include the .h file
    
    int foo() {
      return 42;
    }
    

    And this test to your file with tests:

    TEST_CASE( "test setup" ) {
      CHECK( foo() == 42 );
    }
    

    If you get an error about an undefined reference, double-check your makefile.