Test-First with a Coding Agent: Spec, Red Tests, Then the Code
Relay's first-response SLA, built in three commits: a five-rule spec by hand, 20 agent-written tests with a throwing stub (20 red), then SlaPolicy written to pass them untouched (20 green). A one-word slip, isAfter to !isBefore, is caught only by the edge tests.
What you will learn
- Write a short spec that both the tests and the code follow
- Prompt an agent to write JUnit tests from the spec with a stub that only throws
- Check that every test fails for the right reason before any logic exists
- Let the agent write the code without touching the tests, and verify that with git
Before you start
- The Test Pyramid in Spring Boot
- Using an AI coding agent in IntelliJ
When an agent writes the code and then the tests, the tests tend to describe whatever the code happens to do, bugs included. Flip the order. Give the agent a spec, have it write the tests first, watch every one of them fail, and only then let it write the code. Three steps: spec, red, green.
The whole story in three commits
Spec, Ticket and Priority (by hand: SPEC.md, two records)
Tests from the spec, stub only (agent: SlaPolicyTest 162 lines, SlaPolicy that only throws)
Logic written to pass the tests (agent: 1 file changed, SlaPolicy.java)
Step 1: the spec comes first
This is Relay's first-response rule: every ticket must get a first reply from an agent within a time limit. The spec file is the source of truth:
# Relay - first-response SLA (spec)
## Rules
1. The first-response deadline is the time the ticket was opened plus:
URGENT 1 hour, HIGH 4 hours, NORMAL 8 hours, LOW 24 hours.
2. A ticket with no priority (null) is treated as NORMAL.
3. With no reply yet, a ticket is breached when the current time is after the deadline.
Exactly at the deadline is not breached.
4. With a reply, the ticket is breached only if the first reply came after the deadline.
The current time does not matter any more.
5. Minutes left = whole minutes from now until the deadline, never below 0.
A ticket that already has a reply has 0 minutes left.
## The class to build
`org.studyeasy.s01l06.SlaPolicy`
- `Instant deadline(Ticket ticket)`
- `boolean breached(Ticket ticket, Instant now)`
- `long minutesLeft(Ticket ticket, Instant now)`
Notice rule 3. "Exactly at the deadline is not breached" is the kind of sentence people skip, and it's where bugs hide.
Step 2: tests first, no logic
The first prompt:
Read SPEC.md. We work test-first: tests before the code. 1. Write JUnit 5 tests for every rule in the spec in src/test/java/org/studyeasy/s01l06/SlaPolicyTest.java. Give each test a plain name that says the rule. Work out every expected value from the spec, never from code. 2. Do not write the logic. Create SlaPolicy with the three methods from the spec, and make each body only: throw new UnsupportedOperationException("not built yet"); 3. Run mvn -o -q test and show me that every test fails. Then stop.
The agent reads the spec and the two records, writes a 162-line test class with 20 tests, writes a SlaPolicy whose three methods only throw, and runs Maven. Here's the start of what it wrote:
class SlaPolicyTest {
private static final Instant OPENED_AT = Instant.parse("2026-01-01T00:00:00Z");
private final SlaPolicy policy = new SlaPolicy();
private static Ticket ticket(Priority priority, Instant firstReplyAt) {
return new Ticket(1L, "Printer is on fire", priority, OPENED_AT, firstReplyAt);
}
private static Ticket unanswered(Priority priority) {
return ticket(priority, null);
}
// Rule 1 - deadline is openedAt plus the limit for the priority
@Test
@DisplayName("an urgent ticket is due one hour after it was opened")
void urgentDeadlineIsOneHourAfterOpening() {
assertEquals(Instant.parse("2026-01-01T01:00:00Z"), policy.deadline(unanswered(Priority.URGENT)));
}
// ... HIGH 04:00, NORMAL 08:00, LOW next day 00:00, no priority = NORMAL ...
@Test
@DisplayName("a ticket with no reply is not breached before the deadline")
void unansweredTicketBeforeTheDeadlineIsNotBreached() {
assertFalse(policy.breached(unanswered(Priority.URGENT), Instant.parse("2026-01-01T00:59:59Z")));
}
One fixed opening time, midnight, so every deadline is easy to read. Look at the expected value in the first test: one o'clock, midnight plus one hour. That number comes from the spec, because there's no code yet to copy it from. There's also a pair of edge tests for rule 3 (no reply, exactly 01:00, not breached; one second later, breached) and the same pair for rule 4 with a reply.
[ERROR] Tests run: 20, Failures: 0, Errors: 20, Skipped: 0, Time elapsed: 0.110 s <<< FAILURE! -- in org.studyeasy.s01l06.SlaPolicyTest
Twenty out of twenty red, and every one fails with UnsupportedOperationException: not built yet. That's the point of red first: each test fails for the right reason, and not one passes by accident.
Step 3: now the code, tests untouched
The second prompt: "Now write the logic in SlaPolicy so that every test in SlaPolicyTest passes. Do not change the tests. Keep it short. Run mvn -o -q test at the end."
public class SlaPolicy {
public Instant deadline(Ticket ticket) {
Priority priority = ticket.priority() == null ? Priority.NORMAL : ticket.priority();
return ticket.openedAt().plus(limit(priority));
}
public boolean breached(Ticket ticket, Instant now) {
Instant decidingTime = ticket.firstReplyAt() == null ? now : ticket.firstReplyAt();
return decidingTime.isAfter(deadline(ticket));
}
public long minutesLeft(Ticket ticket, Instant now) {
if (ticket.firstReplyAt() != null) {
return 0;
}
return Math.max(0, Duration.between(now, deadline(ticket)).toMinutes());
}
private static Duration limit(Priority priority) {
return switch (priority) {
case URGENT -> Duration.ofHours(1);
case HIGH -> Duration.ofHours(4);
case NORMAL -> Duration.ofHours(8);
case LOW -> Duration.ofHours(24);
};
}
}
The agent reports 20 tests, zero failures, zero errors, and says the tests are untouched. Don't take its word for it: git log --stat shows the last commit changed one file, SlaPolicy.java. The test file wasn't touched. Run the suite yourself on that commit: the same 20 tests, all green, build success.
Break it: one word changes
On a scratch copy, change decidingTime.isAfter(deadline(ticket)) to !decidingTime.isBefore(deadline(ticket)). It reads almost the same. Run the tests: two failures, and they're the two "exactly at the deadline" tests, one with no reply and one with a reply. Expected false, but was true.
isAfter means strictly later. !isBefore also counts "exactly on time" as late. Only the edge tests can see the difference, and they exist because the spec said so in plain words.
Common mistakes
- Letting the agent see code before it writes tests. The expected values then come from the code, not the spec.
- Skipping the red run. A test that passes against a throwing stub is broken.
- Trusting "tests untouched". Check the diff. One file changed, or it didn't.
- Vague specs. If the spec doesn't say what happens exactly at the deadline, no test will check it.
Try it yourself
Add rule 6 to the spec: weekend hours don't count for LOW tickets. Run the same two prompts. Before you run the second, read the new tests: do their expected values match what you meant?
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Unit Tests With AI for a Spring Boot Service: Mockito Mocks, Given-When-Then and a Green Run
CommentServiceTest runs the real CommentService with three Mockito mocks for its repositories: no Spring, no database, five tests in a fraction of a second. An AI drafts it from a short prompt; we read each test, run it, and learn to read the red message when an expectation is wrong.
Docker for a Spring Boot App: Run the Tests in the Image Build, or Skip Them on Purpose
The blog's Dockerfile runs mvnw package with -DskipTests=${SKIP_TESTS}, false by default, so every docker build runs all 53 tests and a red one means no image. --build-arg SKIP_TESTS=true cuts the package step from 41 to 23 seconds, which is only safe after CI has run the tests.
The Test Pyramid in Spring Boot: Unit, Slice and Whole-App Tests
One small ticket desk, three kinds of test: four plain unit tests in 20 ms, two @WebMvcTest slice tests in 4.4 s, one @SpringBootTest flow in 711 ms. Where each rule belongs, and what you should never test at all.
Mockito and Test Doubles: Stubs, Mocks and Fakes for One Java Class
Test TicketService.close on its own: a stub repository that answers findById, a mock notifier that records send, verify to check both calls, and a HashMap fake that really stores the closed ticket.
