Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Spring Boot
  • Why Spring in 2026: What the Container Does and What Spring Framework 7 Changed
  • A Plain Spring Project, No Boot: Your First Bean With spring-context
  • Inversion of Control and Dependency Injection in Spring: One Program, Built Three Ways
  • Spring Component Scanning: @Component and @ComponentScan Instead of @Bean Methods
  • Spring Autowiring: Spring Fills the Constructor, and When @Autowired Is Needed
  • Two Beans, One Type: Spring @Primary and @Qualifier
  • Spring Bean Scopes: Singleton vs Prototype, One Shared Object or a Fresh One
  • Spring Stereotypes: @Service, @Repository and @Controller Are @Component With a Job Name
  • The Spring Bean Lifecycle: @PostConstruct and @PreDestroy
  • The Mini Blog Wired by Spring: Plain Java vs Spring, Side by Side
  • Spring MVC and SQLite Without Spring Boot: the Mini Blog in the Browser
  • Your First Spring Boot 4 Project: Create It in IntelliJ, Run It, and the Four Files That Matter
  • What Is Spring Boot? Spring Framework 7 With the Decisions Already Made
  • The Project Context File: AGENTS.md and CLAUDE.md for a Spring Boot Project
  • Plan Before Code: a Five-Part Brief, Plan Mode and /goal for a Spring Boot Feature
  • From Design Frames to Thymeleaf Pages: Briefing an AI Agent for a Spring Boot Blog
  • Add, Edit and Delete Posts With a Rich-Text Editor in Spring Boot: Quill, jsoup and th:utext
  • Profile Page and Photo Upload in Spring Boot: Check the File, Shrink It, Keep Your Own Name
  • Building a Feature With an AI Agent, End to End: Comments on a Spring Boot Blog
  • Containerising Spring Boot: a Layered Dockerfile vs Buildpacks
  • GraalVM Native Image and Spring AOT: When It Pays, and What It Costs
  • Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
  • Virtual Threads in Spring Boot: One Property, and the Connection Pool Trap
  • @Async, Named TaskExecutors and Structured Concurrency in Spring Boot
  • Scheduled Jobs in Spring Boot: fixedRate, fixedDelay, cron, and ShedLock for Many Instances
  • Redis in Spring Boot: a Cache, a Rate-Limit Counter and a Job Status Hash
  • Actuator and Micrometer in Spring Boot: Health, Your Own Metrics, and the Four Numbers That Matter
  • Structured Logging and Correlation IDs in Spring Boot: JSON Lines, a Filter and the MDC
  • Dashboards and Alerts for a Spring Boot App: Prometheus, Grafana and One Real Incident
  • Finding a Slow Spring Boot Endpoint: Actuator Timers, EXPLAIN ANALYZE and One Index
  • A GitHub Actions Workflow for a Maven Project: Cache, a Java Matrix and Test Reports That Survive a Red Run
  • The AWS SDK for Java v2 in Spring Boot: Clients as Beans, the Default Credentials Chain and No Keys in Code
  • Attachments in S3 from Spring Boot: Pre-signed Uploads, a 302 to a Pre-signed Download, and Links That Expire
  • CloudWatch for a Spring Boot App: JSON Logs, Micrometer Metrics From Your Own Code, and an Alarm That Reaches a Person
  • Automated Deploy, Smoke Test and Rollback for a Spring Boot App: Green Tests Are Not a Working Deploy
  • Environments, Secrets and Approvals in GitHub Actions: One Image From Staging to Production
  • Distributed Tracing Across Spring Boot Services and Kafka: One Trace ID From the Gateway to the Last Reader, Even Through an Outbox
  • Thymeleaf and htmx in Spring Boot: Live Search and One-Row Updates From Server-Rendered Fragments, With No JavaScript Framework
  • Rate Limiting, Backpressure and Load Shedding in Spring Boot: Bucket4j in Redis, a Bounded Worker Pool and Dropping Low-Priority Work
  • Resilience4j in Spring Boot: A Timeout, One Retry, a Circuit Breaker, a Bulkhead and a Fallback, Measured Against a Slow Dependency
  • Spring Boot Repository and Service Layer: Save and Read Data Without Writing SQL
  • Entities and H2 in Spring Boot: a Post Class Becomes a Table
  • Seed Data and Posts on the Homepage: CommandLineRunner, the Model and th:each
  • Pagination and Sorting on a Spring Boot Homepage: PageRequest In, Page Out
  • Connect Spring Boot to PostgreSQL: Driver, application.yml and the Hikari Pool
  • JPA Entity Mapping: Ids, Enums and Dates, From a Java Class to a Table
  • Spring Data Query Methods: Derived Queries, @Query and Projections
  • The N+1 Problem in JPA: Fetch Types, Join Fetch and Entity Graphs
  • Spring @Transactional: All or Nothing, the Proxy, and the Self-Call Trap
  • Flyway Migrations in Spring Boot: Numbered SQL Files, Seed Data and the History Table
  • Spring Data JPA Auditing and Soft Deletes: Who Changed It, When, and Hiding Instead of Deleting
  • Optimistic Locking with @Version: Two Agents, One Ticket, No Lost Update
  • Finding a Slow Spring Boot Endpoint: Actuator Timers, EXPLAIN ANALYZE and One Index
  • Caching With Spring and Redis: Cache-Aside, a TTL per Kind of Data, Eviction on Edit and Stopping the Stampede
  • A PostgreSQL Read Replica in Spring Boot: Route readOnly Transactions, Size the Pool, Find the Index, Read Your Own Writes
  • A Registration Form With Bean Validation in Spring Boot: @Valid, BindingResult and th:errors
  • Spring Security 7 Form Login, BCrypt and a UserDetailsService on the Account Table
  • Roles and Authorities at Login in Spring Security: From a ROLE Column to hasRole("ADMIN")
  • Menus per Role With Thymeleaf Security Tags: sec:authorize, sec:authentication and an Edit Button for the Author
  • Fixing the Access Bugs: a Rule per Role and an Ownership Check in Spring Security
  • Add, Edit and Delete Posts With a Rich-Text Editor in Spring Boot: Quill, jsoup and th:utext
  • Remember Me and Forgot Password by Email in Spring Boot: a Signed Cookie and a One-Time Link
  • Spring Boot Security Defaults: What One Dependency Gives You for Free
  • The Spring Security Filter Chain and Your Own Rules: 401, 403 and Rule Order
  • Stateless JWT Authentication in Spring Security: Sign Once, Check Every Request
  • Users in the Database with Spring Security: Register, BCrypt and Log In
  • Method Security in Spring: @PreAuthorize, Roles and Who Owns This Ticket
  • CORS and CSRF in Spring Security: Why the Browser Blocks Your SPA, and When CSRF Can Be Off
  • Reviewing AI-Written Spring Code for Security: Four Questions for Every Diff
  • Testing Secured Endpoints in Spring Boot: 401, 403 and 200 with @WithMockUser
  • An API Gateway With Spring Cloud Gateway: Check the JWT Once at the Edge, Pass the Caller Inward, and Know What the Network Now Trusts
  • Unit Tests With AI for a Spring Boot Service: Mockito Mocks, Given-When-Then and a Green Run
  • Docker for a Spring Boot App: Run the Tests in the Image Build, or Skip Them on Purpose
  • The Test Pyramid in Spring Boot: Unit, Slice and Whole-App Tests
  • Mockito and Test Doubles: Stubs, Mocks and Fakes for One Java Class
  • Spring Boot Test Slices: @WebMvcTest with MockMvc and @DataJpaTest
  • Integration Tests with Testcontainers: A Real PostgreSQL for Every Spring Boot Test Run
  • Testing Secured Endpoints in Spring Boot: 401, 403 and 200 with @WithMockUser
  • Test-First with a Coding Agent: Spec, Red Tests, Then the Code
  • Quality and Security Gates for a Maven Project: JaCoCo Coverage, PMD, an SBOM and a Trivy Scan
  • Testing Spring AI Features: a Stub ChatModel, Must-Cite and Must-Refuse Tests, and One Tagged Model Test
  • What Spring AI 2 Is, and Why a Java Team Wants It
  • Spring AI ChatClient: One API for Any Model, and the Model Is a Property
  • Spring AI Prompt Templates: Placeholders, Few-Shot Messages and Versioned Prompt Files
  • Spring AI Structured Output: From Model JSON to a Java Record, and a Real Ticket Triage Feature
  • Streaming Spring AI Answers to the Browser: stream(), a Flux of Server-Sent Events and the Cancel
  • Local Models With Ollama in Spring AI: Profiles, Per-Call Options and What a Smaller Model Costs
  • Testing Spring AI Features: a Stub ChatModel, Must-Cite and Must-Refuse Tests, and One Tagged Model Test
  • Embeddings and pgvector in Spring AI: EmbeddingModel, VectorStore, Distance Operators and the HNSW Index
  • RAG Ingestion in Spring AI: Parse Markdown, Chunk by Section, Embed Into pgvector With Stable Ids
  • Tuning Retrieval in Spring AI: Top-k, a Minimum Score, a Tenant Filter Inside the Query, Hybrid Search and a Reranker
  • Tool Calling in Spring AI 2: @Tool Methods, the ToolCallingAdvisor Loop and a Tool-Call Limit
  • Chat Memory in Spring AI: MessageChatMemoryAdvisor, a Conversation Id, a Window, a Summary and Where the State Lives
  • Building an MCP Server in Java With Spring AI: @McpTool, Stateless Streamable HTTP and Least-Privilege Tools
  • Consuming MCP Servers From Spring AI: a stdio Child Process and a Remote Streamable HTTP Server, Compared
  • A Supervisor and Specialist Agents in Spring AI: Own Prompts, Own Tools, Explicit State and a Menu Checked in Code
  • Choosing a JVM Agent Framework: the Same Two-Step Triage in Spring AI, LangChain4j Agentic and Embabel
  • Observability for Spring AI Calls: a Span per Feature, Token and Spend Counters, Jaeger Traces and Two Prometheus Alerts
  • Evals and Cost Control for a Java Subtitle Service: A Golden Set Scored by Word Error Rate in CI, and the Cost of One Hour of Audio From Micrometer Meters
  1. Blog
  2. /
  3. Spring Boot
  4. /
  5. Testing

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Testing

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)
Three commits: 1 spec written by hand with five rules; 2 the agent writes 20 tests and a stub that throws, 20 of 20 fail; 3 the agent writes SlaPolicy only, the same 20 tests pass. 1. SpecSPEC.md, 5 ruleswritten by hand 2. Red20 tests + throwing stub20 of 20 fail 3. Greenonly SlaPolicy changes20 of 20 pass
The tests came from the spec before any logic existed, so the code had to meet them, not the other way round.

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?

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Spring Boot · 79 of 99

Previous
Testing Secured Endpoints in Spring Boot: 401, 403 and 200 with @WithMockUser
Next post
Quality and Security Gates for a Maven Project: JaCoCo Coverage, PMD, an SBOM and a Trivy Scan

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.

On this page

  • The whole story in three commits
  • Step 1: the spec comes first
  • Step 2: tests first, no logic
  • Step 3: now the code, tests untouched
  • Break it: one word changes
  • Common mistakes
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.