Assertions

Making sure that your program behaves as expected

The way to test that something works with CST is via assertions. CST comes with a lot of assertion macros that help us determine if our program is working as expected. Let's see a basic example to understand how an assertion works. Check out this function:

cst_isnum.c
#include <stdbool.h> // bool type

bool cst_isnum(char ch)
{
    return (ch >= '0' && ch <= '9');
}

Very basic, right? Let's make a test to ensure that it works. We could technically make the test in the same file and it would work, but as seen here, t is common practice to create separate files for tests.

test_cst_isnum.c
#include "cst.h"
#include <stdbool.h> // bool type

bool cst_isnum(char ch);

TEST("cst_isnum", "Pass") {
    ASSERT_TRUE(cst_isnum('4'));
    ASSERT_TRUE(cst_isnum('2'));
}

TEST("cst_isnum", "Fail") {
    ASSERT_TRUE(cst_isnum('a'));
    // Test won't reach this point as previous assertion fails
    ASSERT_TRUE(cst_isnum('4'));
}

So, here we test that '4' and '2' are indeed numeric characters, while 'a' isn't. The first test will pass and the second one will fail. Keep in mind that if an assertion fails, the test stops and fails at said assertion.

Last updated

Was this helpful?