Summary - Testing basics
- C course
- Advanced
- Lesson 72/83
- 5 min
Combine assert and a test framework to write a calculator test.
Summary - Testing basics
In this group you learned assert, a simple test framework, test doubles, coverage and the setup/teardown pattern. Now you'll combine them into a calculator test.
The program defines a calc_add function; test_calculator checks it with assert. Main calls the test and prints a success message. All output is deterministic: when the math is right the program prints "hesap: tamam".
Practice Calculator test
Write int calc_add(int a, int b) that returns a + b. Write void test_calculator(void) with assert(calc_add(2, 3) == 5); and assert(calc_add(0, 0) == 0);. In main call test_calculator(); and print printf("hesap: tamam\n");.
Starter code
#include <stdio.h>
#include <assert.h>
// Write int calc_add(int a, int b) returning a+b
// Write void test_calculator(void) testing with assert
// main: call test_calculator and print "hesap: tamam"
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
#include <assert.h>
int calc_add(int a, int b) {
return a + b;
}
void test_calculator(void) {
assert(calc_add(2, 3) == 5);
assert(calc_add(0, 0) == 0);
}
int main(void) {
test_calculator();
printf("hesap: tamam\n");
return 0;
}Expected output
hesap: tamam
Next steps
You learned the testing basics: assert, a simple framework, stubs, coverage and setup/teardown. These are the core of real test frameworks.
Next steps: full frameworks like Unity or CMocka, interaction testing with mock, HTML coverage reports with lcov, and parameterized tests to run one function with many inputs. The patterns you learned are the foundation of these tools.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When does assert fail?
- When the condition is true
- Always
- Never
- When the condition is false Correct answer
Explanation: assert aborts when the condition is false.
2 Match testing tools
| Term | Meaning |
|---|---|
assert |
Checks condition |
test_run |
Framework core |
stub_time |
Deterministic value |
coverage_counter |
Branch counter |