I have to test a library that provides its own memory allocation routine:
void* allocation_routine(size_t size) throw();
Documentation states that this function allocates at least size bytes of memory (it's allowed to allocate more). By the way the function uses posix_memalign internally, but the implementation may change.
I'm wondering if it's possible to write a unit test for that kind of functions? How can we test whether the required amount of memory was allocated?
UPDATE:
If we can't write a unit test then what is the closest solution?
You cannot write a unit test for this function, because you cannot allocate memory on the heap without a system call. Hence, this is an integration test, as you are unable of isolating the unit under test from the operating system.
I would create a new, small executable that calls allocation_routine
for n
bytes. Depending on what allocation_routine
is supposed to return, you can assert that it's non-nullptr
. Then, write n
bytes into this region of memory. Compile and link it using the address sanitizer (available with both gcc
and clang
), then try to integrate it into the test runner of your application (ctest
etc.).
You might also want to restrict the available heap via the POSIX setrlimit to verify the behvaior when the allocation fails.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With