Using Multiple Test Files

I have multiple test files (.cpp files) containing various tests for source .cpp files. Each test file has its own main() function which I though was okay (Unit Testing Page; Look under “Workflow”)? When I run pio test it gives my an error that there are multiple definitions of ‘main’.

Thank you.

I think the documentation is a little poorly worded there. There can’t be multiple main() functions, but your tests are like a complete by-itself test, as if it was the main() of a program. I think there should only be one main() function that runs all the tests.

2 Likes

Got it, thank you.

Another question…
The documentation mentions using

#ifdef UNIT_TEST
...
#endif

for hiding the main() in the non-testing main.cpp. Where is “UNIT_TEST” defined? When I use those guards around the non-testing main(), and I only have 1 testing main(), it still gives me the “multiple definition of ‘main’” error.

Am I just suppose to #define UNIT_TEST true somewhere manually?

As you can see in the code

When running the test target, the CPP define UNIT_TEST (among UNITY_INCLUDE_CONFIG_H) is defined by PlatformIO. So it’s not defined to true but just defined and can be reacted to with a #ifdef UNIT_TEST (or #if defined(UNIT_TEST)) in code.

Alternatively if you don’t want to compile the code in your src/ folder then you should rather turn of the test_build_project_src option and make sure all to-be-tested code and componentes are in lib/. Or, as you’re currently doing it, build the src/ but surround all non-unit testing code with #ifndef UNIT_TEST.

2 Likes

Very helpful, thank you.