I am using CATCH v1.1 build 14 to unit test my C ++ code.
As part of the testing, I would like to check the outputs of several modules in my code. There is no fixed number of modules; more modules can be added at any time. However, the code for testing each module is identical. Therefore, I think it would be ideal to put the test code in a for
loop. In fact, using catch.hpp
, I confirmed that I can dynamically create sections in a test case, where each section corresponds to a module. I can do this by including the SECTION
macro in a for loop, for example:
#include "catch.hpp" #include <vector> #include <string> #include "myHeader.h" TEST_CASE("Module testing", "[module]") { myNamespace::myManagerClass manager; std::vector<std::string> modList; size_t n; modList = manager.getModules(); for (n = 0; n < modList.size(); n++) { SECTION(modList[n].c_str()) { REQUIRE(/*insert testing code here*/); } } }
(This is not a complete working example, but you get the idea.)
Here is my dilemma. I would like to test the modules myself, so if one module fails, it will continue testing the other modules, rather than interrupting the test. However, how CATCH works, it cancels the entire test case if one REQUIRE
fails. For this reason, I would like to create a separate test case for each module, and not just a separate section. I tried to put the for
loop outside the TEST_CASE macro, but this code does not compile (as I expected):
#include "catch.hpp" #include <vector> #include <string> #include "myHeader.h" myNamespace::myManagerClass manager; std::vector<std::string> modList; size_t n; modList = manager.getModules(); for (n = 0; n < modList.size(); n++) { TEST_CASE("Module testing", "[module]") { SECTION(modList[n].c_str()) { REQUIRE(/*insert testing code here*/); } } }
Perhaps this can be done by writing my own main()
, but I donβt see how to do it exactly. (Would I put my TEST_CASE
code directly in main()
? What if I want to save the TEST_CASE
code in another file? Will it also affect my other, more standard test cases?)
I can also use CHECK
macros instead of REQUIRE
macros to avoid interrupting the test case when the module crashes, but then I get the opposite problem: it tries to continue the test on the module, which was supposed to fail early. If I could just put each module in my test case, this should give me perfect behavior.
Is there an easy way to dynamically create test cases in CATCH? If so, can you give me an example of how to do this? I read the CATCH documentation and searched the Internet, but I could not find any directions on how to do this.