Catch - a test framework for C++
Catch is a testing framework for C++, i.e. a colection of macros that simplify the process of testing functions. To use catch, start by downloading the single header version at: https://raw.githubusercontent.com/catchorg/Catch2/master/single_include/catch2/catch.hpp
The following is a minimal example of how you would use the macros in catch to test a function called inOrder
. Please notice the following:
- the
#define CATCH_CONFIG_MAIN
preprocessor command establishes that this program will not need amain
function, i.e. the catch macros will create that for you! - you need to include the
catch.hpp
function - the
TEST_CASE
block that contains theREQUIRES
are the actual tests that will be performed. As long as the expression inside the REQUIRE is true, the test is passed, otherwise the test is failed.
#define CATCH_CONFIG_MAIN
#include <iostream>
#include "catch.hpp"
using namespace std;
bool inOrder(const vector<int> &v) {
for (int i = 0; i < v.size()-1; i++) {
if (v[i] > v[i+1]) return false;
}
return true;
}
TEST_CASE( "My Tests", "[inOrder]" ) {
REQUIRE( inOrder({2,3,4,10}) == true );
REQUIRE( inOrder({12,3,4,10}) == false );
}
To compile, you need to use C++11 or later and you may need to specify the directory that contains the catch.hpp
:
g++ -o inOrder inOrder.cpp -std=c++11 -I(dir that contains catch.hpp)
Here is an example using a main function:
#define CATCH_CONFIG_RUNNER
#include <iostream>
#include "catch.hpp"
using namespace std;
bool inOrder(const vector<int> &v) {
for (int i = 0; i < v.size()-1; i++) {
if (v[i] > v[i+1]) return false;
}
return true;
}
TEST_CASE( "My Tests", "[inOrder]" ) {
REQUIRE( inOrder({2,3,4,10}) == true );
REQUIRE( inOrder({12,3,4,10}) == false );
}
int main(int argc, char *argv[]) {
int result = Catch::Session().run( argc, argv );
cout << "Hello World\n";
return result;
}