assert testing
- C course
- Advanced
- Lesson 67/83
- 5 min
Learn unit testing with assert.
assert testing
assert aborts the program when a condition is false; it is defined in <assert.h>. If the condition is true nothing happens; if false a message is written to stderr and abort() is called.
This is the simplest form of unit testing: assert(2 + 2 == 4);. Asserts are active in debug builds; in release they are disabled with the NDEBUG macro. In this lesson we always keep them active; they are the fastest way to check small conditions.
Using assert
You write assert(condition); to check a condition. If true execution continues; if false the program stops. This is ideal for checking invariants.
Example: assert(p != NULL); guarantees the pointer is not null. On failure you see the source file and line; this makes assert a powerful debugging tool. After tests it is common to print a success message with printf: printf("test: tamam\n");.
Practice First assert test
Call assert(2 + 2 == 4);. Print the success message with printf("test: tamam\n");. Add the <assert.h> header.
Starter code
#include <stdio.h>
#include <assert.h>
// Check 2 + 2 = 4 with assert
// Print the "test: tamam" message
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
#include <assert.h>
int main(void) {
assert(2 + 2 == 4);
printf("test: tamam\n");
return 0;
}Expected output
test: tamam
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which header defines assert?
- stdlib.h
- stdio.h
- assert.h Correct answer
- string.h
Explanation: answer: assert.h. The assert macro is defined in that header.
2 assert condition
assert(2 + 2 == ____);
assert(2 + 2 == 4);
Explanation: 2 + 2 == 4 is true, the assert passes.
3 Match assert concepts
| Term | Meaning |
|---|---|
assert |
Checks condition |
abort |
Stops program |
NDEBUG |
Disables assert |
stderr |
Error message |