Skip to content

Unit Testing

Tom Sherman edited this page Mar 7, 2017 · 7 revisions

Example

unit_test.h provides a simple framework for running unit tests. This is an example of how math.h is tested. The basic structure looks like:

#include <unit_test.h>
#include <system.h>
#include <math.h>

static bool init_run = false;
static bool tests_run = false;
static char heap[13000];

static void init(void)
{
    initHeap(heap, heap + sizeof(heap));
}

UNIT_TEST;
static void test(void)
{
    ...
    END_TEST;
}

void _main(void)
{
    if (!init_run) { init(); init_run = true;}

    if (!tests_run) { test(); tests_run = true;}
}

Since REQUIRE calls print under the hood, it is necessary to set up the heap. There are 4 macros used for testing:

REQUIRE(condition) - This checks whether condition is true or not. If it's false then a print message is outputted like the ones in the above image.

REQUIRE_FLT_EQ(L, R, tol) - This is for checking equality of floating-point numbers. If |L - R| > tol then this acts just like REUQUIRE when the condition is false.

UNIT_TEST - This is placed in the global scope before any REQUIRE statements are used. IT CAN ONLY BE USED ONCE.

END_TEST - This is placed in a local scope after all tests using REQUIRE have been run.