Assert-based tests in C
A test is a function full of asserts, called from main. No framework needed.
#include <assert.h>
#include <stdio.h>
static size_t count_char(const char *text, char target) {
size_t n = 0;
for (; *text; text++) {
if (*text == target) {
n++;
}
}
return n;
}
static void test_counts_repeats(void) {
assert(count_char("mississippi", 's') == 4);
assert(count_char("mississippi", 'm') == 1);
}
static void test_handles_absence(void) {
assert(count_char("abc", 'z') == 0);
assert(count_char("", 'a') == 0);
}
int main(void) {
test_counts_repeats();
test_handles_absence();
printf("all tests passed\n");
return 0;
}
How it works
- Each test names one behavior and asserts it.
mainruns them and reports when all have passed.- A failing assert aborts and names the file and line.
Keywords and builtins used here
charconstcount_charforifintmainreturnsize_tstatictest_counts_repeatstest_handles_absencevoid
The run, in numbers
- Lines
- 29
- Characters to type
- 534
- Tokens
- 163
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 89 seconds.
Step 1 of 2 in Encore, step 10 of 11 in APIs, errors & testing.