Test patterns
- C course
- Advanced
- Lesson 71/83
- 5 min
Learn common testing patterns.
Test patterns
Test patterns are templates that solve recurring test needs. The best known is setup/teardown: preparation before a test and cleanup after. This pattern keeps tests independent of each other.
setup(void) is called before the test; it prepares resources. teardown(void) is called after; it releases resources. A test function runs in between. This is the basis of the fixture mechanism in real frameworks (Unity, CMocka).
Setup/teardown skeleton
A setup function prepares resources and returns a success flag; teardown cleans up. In main the order is: setup(); test(); teardown();.
Example: int setup(void) { printf("kuruldu\n"); return 1; } and void teardown(void) { printf("yıkıldı\n"); }. Main: setup(); printf("test: tamam\n"); teardown();. Output: kuruldu, test: tamam, yıkıldı. These three lines are the minimum skeleton of a real fixture.
Practice Setup/teardown pattern
Write int setup(void): printf("kuruldu\n"); return 1;. Write void teardown(void): printf("yıkıldı\n");. In main call in order setup();, printf("test: tamam\n");, teardown();.
Starter code
#include <stdio.h>
// Write int setup(void): print "kuruldu", return 1
// Write void teardown(void): print "yıkıldı"
// main: call setup, test message, teardown in order
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
int setup(void) {
printf("kuruldu\n");
return 1;
}
void teardown(void) {
printf("yıkıldı\n");
}
int main(void) {
setup();
printf("test: tamam\n");
teardown();
return 0;
}Expected output
kuruldu test: tamam yıkıldı
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match pattern steps
| Term | Meaning |
|---|---|
setup |
Preparation |
teardown |
Cleanup |
test |
Running part |
fixture |
Skeleton |
2 When is setup called?
- To run the test
- For post-test cleanup
- For pre-test preparation Correct answer
- For the test report
Explanation: setup prepares resources before the test.
3 setup return value
int setup(void) { printf("kuruldu
"); return ____; }
int setup(void) { printf("kuruldu
"); return 1; }
Explanation: setup returns 1 as a success flag.