Sub topic 16
Writing Tests That Stay Useful
A test is useful when it fails only because something is really broken. A test that fails at random, breaks after every small code change, or takes minutes to run soon gets ignored. In this chapter you will learn the habits that keep tests trustworthy for years, not weeks.
Why Good Tests Go Bad
Most tests start out fine. Problems show up later, as the code grows. These are the usual ways a test goes bad:
- Flaky tests. A flaky test passes sometimes and fails sometimes, even though nobody changed the code. People learn to rerun it until it passes, so it stops catching real bugs.
- Brittle tests. A brittle test breaks whenever you change how the code works inside, even when the result stays the same. Every refactor becomes a chore.
- Slow tests. If the suite takes ten minutes, people stop running it before each commit.
- Confusing tests. When a test fails and nobody can tell what it checks, it gets deleted or disabled.
The good news is that a few simple rules prevent almost all of these problems.
The FIRST Rules
Many teams use the word FIRST to remember what a good unit test looks like.
| Letter | Rule | What it means in practice |
|---|---|---|
| F | Fast | Each test runs in milliseconds. No real network, database, or long waits. |
| I | Independent | Tests do not depend on each other or on running in a certain order. |
| R | Repeatable | The test gives the same result on every machine, every day, every time. |
| S | Self-validating | The test passes or fails on its own. Nobody reads printed output to decide. |
| T | Timely | You write the test close to the time you write the code, not months later. |
The sections below show how to follow the rules that cause the most trouble: Independent and Repeatable.
Keep Tests Independent
Shared state is data that more than one test can read and change. It is the main reason tests depend on each other. A static field is the most common kind, because there is only one copy for the whole test class.
Here is a bad example:
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
class BadOrderTest {
// One list shared by every test: this is the problem.
private static final List<String> orders = new ArrayList<>();
@Test
void addOneOrder() {
orders.add("book");
assertEquals(1, orders.size());
}
@Test
void addTwoOrders() {
orders.add("pen");
orders.add("cup");
assertEquals(2, orders.size());
}
}If addOneOrder runs first, addTwoOrders sees three items and fails. If the order flips, the other test fails. JUnit does not promise any fixed order, so this suite can pass today and fail tomorrow.
The fix is to give every test its own fresh data. JUnit 5 already creates a new instance of the test class for each test method. So a plain instance field, without static, starts empty every time:
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
class GoodOrderTest {
// A new list for every test, because JUnit makes a new GoodOrderTest each time.
private final List<String> orders = new ArrayList<>();
@Test
void addOneOrder() {
orders.add("book");
assertEquals(1, orders.size());
}
@Test
void addTwoOrders() {
orders.add("pen");
orders.add("cup");
assertEquals(2, orders.size());
}
}Keep Tests Repeatable
A test is repeatable when nothing outside your control can change its result. The usual troublemakers are the current time, random numbers, real files, and the network.
Look at this class. It picks a greeting based on the clock:
import java.time.LocalTime;
public class HardToTestGreeter {
public String greet() {
int hour = LocalTime.now().getHour();
return hour < 12 ? "Good morning" : "Good afternoon";
}
}A test that expects "Good morning" passes before noon and fails after lunch. You cannot fix this inside the test. You have to fix the design.
The fix is to pass the time source in from outside. Java has a class for this called java.time.Clock. A Clock is an object that tells the code what time it is. Real code uses the system clock. Tests use a fixed clock that always returns the same moment.
import java.time.Clock;
import java.time.LocalTime;
public class Greeter {
private final Clock clock;
public Greeter(Clock clock) {
this.clock = clock;
}
public String greet() {
int hour = LocalTime.now(clock).getHour();
return hour < 12 ? "Good morning" : "Good afternoon";
}
}In production you write new Greeter(Clock.systemDefaultZone()). In tests you control the time completely:
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import org.junit.jupiter.api.Test;
class GreeterTest {
private Clock fixedAt(String isoTime) {
return Clock.fixed(Instant.parse(isoTime), ZoneOffset.UTC);
}
@Test
void saysGoodMorningBeforeNoon() {
Greeter greeter = new Greeter(fixedAt("2026-01-05T09:00:00Z"));
assertEquals("Good morning", greeter.greet());
}
@Test
void saysGoodAfternoonFromNoon() {
Greeter greeter = new Greeter(fixedAt("2026-01-05T12:00:00Z"));
assertEquals("Good afternoon", greeter.greet());
}
}The second test checks exactly 12:00. That is an edge case, a value right at the border where the behavior changes. Bugs like <= written instead of < hide at borders, so they are worth a test of their own.
The same idea works for random numbers. Pass in a java.util.Random object, and give tests a new Random(42). The number 42 is a seed, a starting value that makes the "random" numbers come out the same every run.
Test Behavior, Not Internals
Behavior is what the code does from the outside: what it returns, what it throws, what it saves. Internals are the private details of how it gets there, such as helper methods or which list type it uses.
Good tests check behavior. If you rewrite a sorting method to use a faster algorithm, the sorted result is the same, so a good test keeps passing. A test that checks which private helper was called would break, even though nothing is wrong.
Some practical rules:
- Call only public methods in your tests.
- Do not change
privateto public just so a test can reach it. - With mocks, verify only the calls that matter to the result, such as "the order was saved." Do not verify every small call along the way.
Keep Logic Out of Tests
A test should be so simple that it cannot have its own bugs. Avoid if, loops, and calculations inside test methods.
Watch out for this trap:
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class PriceTest {
static int priceWithTax(int price) {
return price + price * 20 / 100;
}
@Test
void weakTestRepeatsTheFormula() {
int price = 50;
// Copies the same formula, so a wrong formula still passes.
assertEquals(price + price * 20 / 100, priceWithTax(price));
}
@Test
void strongTestUsesAKnownAnswer() {
assertEquals(60, priceWithTax(50));
}
}The weak test copies the code's own formula. If the formula is wrong, the test is wrong in the same way and still passes. The strong test uses a number you worked out by hand. It is shorter, too.
One Behavior per Test
Each test should check one behavior and have a name that says what it is. When saysGoodAfternoonFromNoon fails, you know what broke without reading the code. One behavior can still need several assertions, for example checking both the size and the contents of a list. That is fine. The test still has one reason to fail.
The flowchart below sums up the checks to run on any new test.
Exercises
Exercise
A test class has a field private static int counter = 0;. Two tests each increase it and then check its value. The suite passes in the IDE but fails on the build server. What is the most likely cause, and how do you fix it?
Show answer
The tests share the static field, so the result depends on which test runs first, and the order can differ between machines. Remove static so each test gets a fresh field (JUnit makes a new test class instance per test), or reset the value in a @BeforeEach method.
Exercise
A method isWeekend() calls LocalDate.now() inside it. Why is it hard to test, and what change makes it repeatable?
Show answer
Its result depends on the real current date, so a test passes only on some days. Pass a java.time.Clock in through the constructor and call LocalDate.now(clock). Tests can then use Clock.fixed(...) to choose a Saturday or a Monday.
Exercise
A test checks a discount with assertEquals(total * 0.9, service.discounted(total)). What is wrong with this assertion?
Show answer
It repeats the formula from the production code, so a wrong formula would still pass. Use a value you worked out by hand, such as assertEquals(90.0, service.discounted(100.0)).