Combo Projects
Often times, you want to build a "real" program with a main function that makes use of code you are writing. But at the same time, you want to be able to run unit tests on that code. You can't do that all in one program. A program can only have a single main functions and the unit testing system will create its own main function.
However, we can set up two separate projects in the same folder. One Makefile will be used to describe two build targets - the program and the tests.
Combo Project Template
The ComboProject
template is what you should use to make a project that will have a
"real" program and a testing program.
It has the code for two different programs. The "real" program that uses the code from
main.cpp
and a tester program that uses the code from tests.exe
.
To select whether you are building and running the unit test or regular project, Go to the Run and Debug view:
And then select Run Program, Run Program (Mac), Run Tests, or Run Tests (Mac) as appropriate:
Adding Functions
To create functions that will be tested by your tests and also available in the "real" program, you need to place them in a separate file. Here is how to do so:
Add new .h and .cpp files to the project folder and name them something like
functions.h
andfunctions.cpp
.Add the .cpp file to the
SHARED_FILES
line of yourMakefile
. It should look like:SHARED_FILES = functions.cpp
If you add more than one new .cpp file, put a space between each name:
functions.cpp other.cpp
All of the .cpp files will need to include the .h file:
#include "functions.h"
To test the setup, add this function declaration to your
.h
:int foo();
This definition to your
.cpp
:int foo() { return 42; }
This test to your file with tests:
TEST_CASE( "test setup" ) { CHECK( foo() == 42 ); }
Then build and run the test program.
Once the test program is working, change your main function in the "real" project to this:
int main() { cout << "foo() produces " << foo() << endl; }
Then build and run the "real" program.