01 / 21

Writing
Test Cases in Java

Learn how to write simple test cases and predict expected outputs for Java methods: a foundational skill for building reliable software.

AP Computer Science A

What Is a Test Case?

A test case is a specific scenario you create to verify that a method behaves correctly. It consists of three parts: the input you provide, the action you perform (calling the method), and the expected output you predict.

Input
The arguments you pass to the method
Action
Calling the method with those inputs
Expected Output
The result you predict the method should return

Why Write Tests?

Testing is not just for big companies. Even in a classroom, writing test cases helps you think through your logic before and after coding. It catches bugs early and builds confidence that your code works.

1
Catch bugs early: find mistakes before your teacher does.
2
Clarify requirements: writing expected outputs forces you to understand what the method should do.
3
Refactor safely: when you change code, tests tell you if something broke.

Anatomy of a Simple Test

ARRANGE Set up inputs ACT Call the method ASSERT Check expected output
// Arrange
int input = 5;
// Act
int result = MathUtils.square(input);
// Assert: expected output is 25
System.out.println(result == 25); // true

The Golden Rule of Testing

Independent
Does not depend on other tests or external state
Specific
Tests exactly one behavior with clear inputs and outputs
Repeatable
Produces the same result every time it runs

Test Cases vs Debugging

Test Cases Debugging
When Before and after writing code After a bug is found
Purpose Prevent bugs proactively Fix bugs reactively
Approach Systematic: planned inputs and outputs Investigative: trace execution flow
Reusable? Yes: run again after changes No: one-time effort

How to Write a Test Case

1
Read the method signature: identify the parameter types and return type.
2
Understand the specification: what should this method do?
3
Choose inputs: pick a typical value, an edge case, and a boundary value.
4
Compute expected output by hand: trace the logic yourself before running.
5
Write the test: call the method, compare actual vs expected, print the result.

Choosing Good Inputs

Not all inputs are equally useful. A strong set of test cases covers normal cases, edge cases, and boundary values.

Normal Case
A typical, expected input: e.g., passing 7 to a method that finds the absolute value.
Edge Case
An unusual or extreme input: e.g., passing 0, an empty string, or null.
Boundary Value
Values at the limits: e.g., Integer.MAX_VALUE, first/last index of an array.

Example 1: Testing isEven

public static boolean isEven(int n) { return n % 2 == 0; }
1
Normal case: isEven(4) → expected: true
2
Normal case: isEven(7) → expected: false
3
Edge case: isEven(0) → expected: true
4
Negative: isEven(-3) → expected: false

Example 1: Test Code

public static void main(String[] args) { // Test 1: normal even System.out.println(isEven(4) == true); // true // Test 2: normal odd System.out.println(isEven(7) == false); // true // Test 3: edge case zero System.out.println(isEven(0) == true); // true // Test 4: negative odd System.out.println(isEven(-3) == false); // true }

Example 2: Testing maxOfThree

public static int maxOfThree(int a, int b, int c) { if (a >= b && a >= c) return a; if (b >= a && b >= c) return b; return c; }
1
First is max: maxOfThree(10, 5, 3) → expected: 10
2
Second is max: maxOfThree(2, 9, 4) → expected: 9
3
Third is max: maxOfThree(1, 3, 7) → expected: 7
4
All equal: maxOfThree(5, 5, 5) → expected: 5
5
Negatives: maxOfThree(-1, -5, -2) → expected: -1

Example 3: Testing countVowels

public static int countVowels(String s) { int count = 0; for (char c : s.toLowerCase().toCharArray()) { if ("aeiou".indexOf(c) != -1) count++; } return count; }
1
Normal: countVowels("hello") → expected: 2
2
All vowels: countVowels("aeiou") → expected: 5
3
No vowels: countVowels("xyz") → expected: 0
4
Empty string: countVowels("") → expected: 0
5
Mixed case: countVowels("ApPlE") → expected: 2

The Power of Edge Cases

Edge cases are the inputs most likely to reveal bugs. They live at the boundaries of what your method handles. Always ask: "What happens at the extremes?"

MIN_VALUE 0 MAX_VALUE EDGE EDGE EDGE Normal inputs (well-covered) Bugs hide at edges Bugs hide at edges

A Reusable Test Helper

Instead of writing println for every check, create a small helper method that prints a clear pass/fail message:

public static void check(String label, int actual, int expected) { if (actual == expected) { System.out.println("PASS: " + label); } else { System.out.println("FAIL: " + label + " | expected " + expected + " but got " + actual); } }
// Usage: check("countVowels hello", countVowels("hello"), 2); check("countVowels empty", countVowels(""), 0);

Common Mistakes in Test Cases

✕ Only Testing Happy Path
Testing only typical inputs and skipping edge cases like 0, negatives, empty strings, or null.
✕ Wrong Expected Output
Computing the expected output incorrectly by hand, then assuming the method is broken when it is actually correct.
✕ Testing Multiple Things
Combining several behaviors in one test. When it fails, you cannot tell which behavior is broken.

Test Case Checklist

Category What to Test Example
Normal Case Typical, expected values isEven(4) → true
Edge Case (Zero) An extreme or minimal value isEven(0) → true
Edge Case (Empty) Empty string or collection countVowels("") → 0
Negative Numbers Values outside the positive domain maxOfThree(-1,-5,-2) → -1
Equal Inputs All inputs are identical maxOfThree(5,5,5) → 5

Question 1 of 5

Given the method public static int abs(int n), which returns the absolute value of n, what is the expected output of abs(-7)?

Question 2 of 5

Which of the following is the best edge case to test for a method public static double average(int[] arr)?

Question 3 of 5

A student writes this test: greet("Bob") returns "Hello, Bob". What is the biggest weakness of testing only this case?

Question 4 of 5

In the Arrange-Act-Assert pattern, what does the "Assert" step do?

Question 5 of 5

Which additional test case would most improve this test suite?