01 / 21

Writing Test Cases
in C++

Learn how to write simple test cases that verify your code produces expected outputs and catch bugs before they become problems.

C++

What Is a Test Case?

A test case is a small piece of code you write to check whether a function produces the correct result. You give it a known input, run the function, and compare the actual output to the expected output.

Known Input Your Function Actual Output
\(==\) Expected?

Why Write Test Cases?

✓ Catch Bugs Early
Find errors before your program reaches users or graders.
✓ Build Confidence
Know your code works correctly because you have proof.
✓ Safe Refactoring
Change code freely: if tests still pass, nothing broke.

Anatomy of a Test Case

Every test case has three essential parts, often called the Arrange-Act-Assert pattern:

1
Arrange: Set up the input values and any preconditions your function needs.
2
Act: Call the function with those inputs and capture the result.
3
Assert: Compare the actual result against the expected output and report pass or fail.

The Core Testing Pattern

#include <iostream> using namespace std; // Function to test int add(int a, int b) { return a + b; } int main() { // Arrange int expected = 5; // Act int actual = add(2, 3); // Assert if (actual == expected) { cout << "PASS" << endl; } else { cout << "FAIL: expected " << expected << " but got " << actual << endl; } return 0; }

Using assert() for Tests

C++ provides a built-in assert() macro from <cassert>. If the condition is false, the program crashes with an error message showing the exact line that failed.

#include <cassert> #include <iostream> using namespace std; int multiply(int a, int b) { return a * b; } int main() { assert(multiply(3, 4) == 12); // passes assert(multiply(0, 7) == 0); // passes assert(multiply(-2, 5) == -10); // passes cout << "All tests passed!" << endl; return 0; }

assert() vs if/else Testing

assert() if/else Pattern
Header <cassert> None needed
On Failure Crashes program Prints message, continues
Shows All Results No, stops at first fail Yes, runs all tests
Code Length One line 3-5 lines per test
Best For Quick checks Detailed reporting

Choosing Edge Cases

Edge cases are unusual or extreme inputs that often reveal bugs. Good testers think beyond the "happy path" and deliberately try inputs that could break things.

Zero
Pass 0 as an argument: does the function handle it?
Negatives
Negative numbers can break assumptions about signs.
Empty Input
Empty strings or empty arrays are common crash sources.
Large Values
Very large numbers can cause overflow or timeouts.

Step-by-Step Test Writing

1
Identify the function you want to test and understand its expected behavior.
2
Pick normal inputs: choose typical values where you can compute the correct answer by hand.
3
Pick edge cases: zero, negatives, empty input, maximum values, and boundary conditions.
4
Write the assert or if/else for each input-output pair.
5
Run and read output: fix any failures, then add more tests as you think of new scenarios.

Example 1: Testing isEven()

bool isEven(int n) { return n % 2 == 0; } int main() { // Normal cases assert(isEven(4) == true); assert(isEven(7) == false); // Edge cases assert(isEven(0) == true); // zero assert(isEven(-3) == false); // negative odd assert(isEven(-6) == true); // negative even cout << "All isEven tests passed!" << endl; }

Example 2: Testing maxOfThree()

int maxOfThree(int a, int b, int c) { if (a >= b && a >= c) return a; if (b >= a && b >= c) return b; return c; } void testMaxOfThree() { // Max in each position assert(maxOfThree(9, 3, 5) == 9); // max is 1st assert(maxOfThree(2, 8, 4) == 8); // max is 2nd assert(maxOfThree(1, 3, 7) == 7); // max is 3rd // Ties and negatives assert(maxOfThree(5, 5, 5) == 5); // all equal assert(maxOfThree(-1, -5, -3) == -1); cout << "All maxOfThree tests passed!" << endl; }

Example 3: Testing String Functions

#include <string> using namespace std; string greet(string name) { return "Hello, " + name + "!"; } void testGreet() { // Normal case assert(greet("Alice") == "Hello, Alice!"); // Edge: empty string assert(greet("") == "Hello, !"); // Edge: string with spaces assert(greet("Bob Smith") == "Hello, Bob Smith!"); cout << "All greet tests passed!" << endl; }

Organizing Multiple Tests

As your project grows, group tests into dedicated functions and call them all from main(). This keeps your code clean and each test function focused.

void testAdd() { assert(add(2, 3) == 5); assert(add(0, 0) == 0); assert(add(-1, 1) == 0); cout << " add: PASSED" << endl; } void testMultiply() { assert(multiply(3, 4) == 12); assert(multiply(0, 99) == 0); cout << " multiply: PASSED" << endl; } int main() { cout << "Running tests..." << endl; testAdd(); testMultiply(); cout << "All tests passed!" << endl; }

Test Coverage Thinking

Good coverage means your tests exercise all the important paths through your function. Think of inputs as falling into categories:

Your Function Normal Inputs Boundary Values Edge Cases Invalid Inputs

Common Mistakes

✕ Only Testing Happy Path
Writing tests only for typical inputs and missing zero, negatives, or empty strings.
✕ Wrong Expected Value
Calculating the expected answer incorrectly. This can cause a correct function to fail its test, or a buggy function to pass if your expectation matches the bug.
✕ Vague Failure Messages
When using an if/else pattern, printing just "Test Failed" is unhelpful. Always print the expected and actual values.

Test Case Cheat Sheet

Concept What to Do Example
Arrange Set up inputs and expected value int expected = 5;
Act Call the function int result = add(2, 3);
Assert Compare actual vs expected assert(result == 5);
Edge Case Test zero, negatives, empty assert(add(0,0) == 0);
Organize Group into test functions void testAdd() { ... }

Question 1 of 5

What are the three parts of the Arrange-Act-Assert pattern?

Question 2 of 5

What happens when an assert() statement's condition evaluates to false?

Question 3 of 5

You are testing a function abs(int n) that returns the absolute value. Which set of test inputs provides the best coverage?

Question 4 of 5

What critical edge case is missing from these tests?

Question 5 of 5

Which of the following is the most important missing test case?