Simple C++ unit test bench and framework
Find a file
Antoine Mazeas fd8941d927 upgrade cmake min version
Signed-off-by: Antoine Mazeas <antoine@karthanis.net>
2025-04-26 09:27:38 +02:00
include Improve memory mgmt 2021-09-12 23:35:51 +02:00
src Handle all types of exceptions in tests 2021-09-25 15:13:16 +02:00
test Add assert_is_true, assert_is_false 2021-09-08 18:45:24 +02:00
.gitignore Save state 2021-09-02 18:37:21 +02:00
CMakeLists.txt upgrade cmake min version 2025-04-26 09:27:38 +02:00
LICENSE Initial commit 2021-09-01 17:20:49 +00:00
README.md Add grouping header file for easy include in clients 2021-09-12 19:38:43 +02:00

faults

Simple and awkward C++ unit test bench and framework.

Usage

Given a function assert_equals that needs to be tested:

#include <faults/faults.hpp>

using namespace faults;

class test_assertequals_intint_should_throw : public Case {
private:
  void _test() {
    try {
      // here we call the function to test
      // we want this to throw
      assert_equals(1, 2);
    } catch (AssertException ae) { return; }
    throw AssertException("assert_equals(1, 2) did not throw an exception.");
  }
public:
  test_assertequals_intint_should_throw()
    : Case("assert_equals(int, int) should throw") {}
};

int main(void) {
  Suite s("Assertion tests");
  s.register_case(new test_assertequals_intint_should_throw);
  s.run_and_collect();
  s.report();
  return s.has_any_failure();
}

Design

A test case is represented by a class derived from the abstract faults::Case class, implementing the virtual private method ::_test.

This method returns void, so it's not necessary to return anything explicitly. However, any failing assertions should throw a faults::AssertException to be caught and processed by the framework.

A test suite is a set of test cases: the class faults::Suite exposes the method ::register_case(Case *) which takes a pointer to an instance of a class derived from faults::Case as explained above. Calling ::register_case(Case *) inserts the passed pointer into an internal collection, which is iterated upon when calling ::run_and_collect().

The test suite is executed by calling ::run_and_collect(), which will iterate upon all test cases and call their ::resolve() method (which internally calls the virtual member ::_test()). Each test case emits a result in the form of a faults::Result object, which is recorded into either a "passed" or "failed" collection. The method faults::Suite::has_any_failure() returns true whenever there has been at least one failing test case.

A test suite can output the outcome of its run by calling ::report(). This must only be done after calling ::run_and_collect() in order to have results in store.

Building and testing

The build system is cmake. To build faults, do:

cmake . -Bbuild
cmake --build build --clean-first

To run the tests, after building, do:

cd build/test
ctest -V