I'm writing a dynamic array for a personal project and am trying to unit test all the functions. I'm trying to write a unit test for util_dyn_array_check_index() but am having problems doing so because I made the design decision to call exit(-1) if there is an index out of bounds. I want to check in my unit test that it calls exit() when provided with an invalid index. But if I ever give it an invalid index, it just exits my testing program. Is it possible to somehow catch that a call to exit() was thrown, or redefine exit() in my testing program to prevent it from ending the tests?
From this answer I've looked into atexit(), but it looks like that doesn't stop an exit, just performs one or more user-defined functions before exiting. This doesn't work for me because I have other tests to run after this one. My last thought is I could make util_dyn_array_check_index() a macro instead of a function, and redefine exit() to be a different function in my testing program, but I'd rather not make it a macro if I can avoid it.
Here's my code:
The details of this struct don't really matter, just provided for completeness
//basically a Vec<T>
typedef struct {
//a pointer to the data stored
void * data;
//the width of the elements to be stored in bytes
size_t stride;
//the number of elements stored
size_t len;
//the number of elements able to be stored without reallocating
size_t capacity;
} util_dyn_array;
Here is the function I want to test.
//exits with -1 if index is out of bounds
inline void util_dyn_array_check_index(util_dyn_array * self, size_t index) {
if (index >= self->len) {
exit(-1);
}
return;
}
Here is a skeleton of what I would like the test to be (omitted some macro magic I'm using to make writing tests nicer, for clarity).
bool test_dyn_array_check_index() {
util_dyn_array vector = util_dyn_array_new(sizeof(int), 16);
for(int i = 0; i < 16; i++) {
util_dyn_array_push(&vector, (void*)&i);
}
for(int i = 0; i < 16; i++) {
//if nothing happens, its successful
util_dyn_array_check_index(&vector, i);
}
//somehow check that it calls exit without letting it crash my program
{
util_dyn_array_check_index(&vector, 16);
}
return true;
}
Obviously I could change my code to return a bool or write to errno, but I'd prefer it to exit as its usually an unrecoverable bug.