Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

How would you write automated tests for a Spring Boot service that uses ChatClient to summarise support tickets, without calling a real model on every build?

We unit test everything around the model by replacing the ChatModel, or the ChatClient call, with a fake that returns fixed responses, and we test prompt construction and output parsing as separate pieces. A small set of tests calls the real model in a scheduled job rather than on every commit, using a fixed dataset of example tickets with the key facts each summary must contain, and those tests assert properties such as contains the key facts, is valid JSON and stays under a length limit, instead of exact text.

Why this question is asked

A service that calls a model is still a service: it builds a request, calls something, parses the answer and decides what to do with it. Most of its bugs are in that ordinary code, and we can test it as quickly and reliably as anything else. The model call itself is slow, costs money and gives a different answer each time, so it cannot run on every build. Interviewers ask this to see whether we can split the problem into the part we test like normal code and the part we evaluate like a model. In this answer, we will look at the service under test, fake the model for unit tests, test prompt building and parsing separately, write property assertions, and set up the scheduled tests against the real model.

1The Service Under Test

Our service takes a support ticket, asks the model for a summary and a category, and returns a typed result. It also has rules of its own: very long tickets are truncated, and a summary the model cannot produce leads to a fallback.

Java
@Service
class TicketSummariser {
private final ChatClient chat;
TicketSummariser(ChatClient chat) { this.chat = chat; }
TicketSummary summarise(Ticket t) {
String body = t.body().length() > 8_000 ? t.body().substring(0, 8_000) : t.body();
try {
return chat.prompt()
.system("Summarise the support ticket in at most 2 sentences and pick a category.")
.user(u -> u.text("Subject: {s}\nBody: {b}").param("s", t.subject()).param("b", body))
.call()
.entity(TicketSummary.class);
} catch (RuntimeException e) {
return TicketSummary.unavailable(t.id());
}
}
}
record TicketSummary(String summary, Category category) {
static TicketSummary unavailable(String id) { return new TicketSummary("Summary unavailable", Category.UNKNOWN); }
}

Notice how much of this is ours: the truncation, the prompt template, the parsing into a record and the fallback. None of it needs a real model to test.

2Faking the Model in Unit Tests

ChatClient is built on the ChatModel interface, so the simplest fake is a small ChatModel implementation that records the prompt it received and returns a fixed response. We then build a real ChatClient on top of it, which means our test exercises the real Spring AI request building and output conversion, only without the network. A Mockito mock of ChatModel also works; a hand-written fake is easier to read and to reuse.

Java
class FakeChatModel implements ChatModel {
final List<Prompt> prompts = new ArrayList<>();
private final String reply;
FakeChatModel(String reply) { this.reply = reply; }
@Override public ChatResponse call(Prompt prompt) {
prompts.add(prompt);
return new ChatResponse(List.of(new Generation(new AssistantMessage(reply)))); // constructors vary by version
}
}
@Test
void returnsParsedSummary() {
var model = new FakeChatModel("{\"summary\":\"Customer was charged twice.\",\"category\":\"BILLING\"}");
var service = new TicketSummariser(ChatClient.builder(model).build());
TicketSummary s = service.summarise(new Ticket("T-1", "Double charge", "I was charged twice on 3 Nov"));
assertThat(s.category()).isEqualTo(Category.BILLING); // passes
assertThat(model.prompts.get(0).getContents()).contains("charged twice on 3 Nov"); // passes
}
@Test
void fallsBackWhenTheAnswerIsNotJson() {
var model = new FakeChatModel("Sure! Here is a summary: the customer ...");
var service = new TicketSummariser(ChatClient.builder(model).build());
assertThat(service.summarise(ticket()).category()).isEqualTo(Category.UNKNOWN); // passes
}

These tests run in milliseconds, cost nothing and give the same result every time. The second test is the important one: it feeds the kind of malformed answer a real model occasionally produces and checks that our fallback works. We can write fakes for every failure we have seen, such as a code fence around the JSON, an unknown category value or an exception from the provider.

3Testing Prompt Construction and Parsing Separately

The service mixes two concerns that are easier to test apart. Prompt construction decides what the model sees: the truncation at 8,000 characters, the template, which fields are included and that personal data such as card numbers is removed. Output parsing decides what we do with what comes back. If we extract each into its own small class, a PromptBuilder and a parser or validator, we can test them directly with many inputs and no ChatClient at all.

Java
@Test
void truncatesLongBodies() {
Prompt p = promptBuilder.build(new Ticket("T-2", "Long", "x".repeat(20_000)));
assertThat(p.getContents().length()).isLessThan(8_500); // passes: body cut to 8,000
}
@Test
void masksCardNumbers() {
Prompt p = promptBuilder.build(new Ticket("T-3", "Card", "My card 4111 1111 1111 1111 failed"));
assertThat(p.getContents()).doesNotContain("4111 1111 1111 1111"); // passes
}

4Asserting Properties, Not Exact Text

When we do call a real model, the same ticket can produce Customer was charged twice. on one run and The customer reports a duplicate charge. on the next. Both are correct, so a test that compares exact strings fails randomly and teaches the team to ignore it. Instead we assert properties that every good answer has: the JSON parses into the record, the category is the expected one, the summary mentions the key facts, such as charged twice, and it stays within two sentences or 300 characters. For facts that can be phrased many ways, we check a few accepted keywords, or use a second model as a judge, accepting that the judge can be wrong too.

5A Fixed Dataset and Scheduled Real-Model Tests

We keep a fixed dataset of perhaps 30 to 50 real, anonymised tickets, each with the expected category and the key facts its summary must contain. A separate test class runs this dataset against the real model. It is tagged so that the normal build excludes it, and a scheduled CI job runs it nightly and whenever the prompt or the model version changes, with the API key from the CI secret store. Because results vary, we judge the run as a whole, for example at least 90 percent of tickets pass, rather than failing on any single ticket, and we keep the results over time so a drop after a model update is visible.

Java
@Tag("live-model") // excluded from the default build
@SpringBootTest
class TicketSummariserLiveTest {
@Autowired TicketSummariser summariser;
@Test
void meetsQualityBarOnDataset() {
List<Example> examples = Examples.load("tickets-v3.json"); // 40 tickets with expected facts
long passed = examples.stream().filter(ex -> {
TicketSummary s = summariser.summarise(ex.ticket());
return s.category() == ex.expectedCategory()
&& ex.keyFacts().stream().allMatch(f -> s.summary().toLowerCase().contains(f))
&& s.summary().length() <= 300;
}).count();
assertThat(passed).isGreaterThanOrEqualTo(Math.round(examples.size() * 0.9)); // 38 of 40
}
}
Where each kind of test runs
TestModelWhen it runsAsserts
Service logic with fake ChatModelFakeEvery commitParsing, fallback, flow
Prompt builderNoneEvery commitTemplate, truncation, masking
Output parser and validatorNoneEvery commitMalformed and edge answers
Dataset against real modelRealNightly, on prompt or model changeKey facts, valid JSON, length
Fast deterministic tests on every build; the real model on a schedule.

6Follow-up questions

Should I use Testcontainers with a local model, such as Ollama, instead of a fake?

It is a useful middle layer for checking that the integration and configuration work end to end without a paid API. But a small local model behaves differently from the production model, so it does not replace the scheduled tests against the real one, and it is too slow for every unit test.

How do I test streaming code?

The fake ChatModel can also implement stream() and return a Flux of chunks, for example with Flux.just("Customer ", "was charged ", "twice."). StepVerifier from Reactor then checks that the service assembles or forwards the chunks correctly and handles an error in the middle of the stream.

Can we record real responses and replay them?

Yes, recording a set of real answers and replaying them through the fake is a good way to get realistic test inputs, including the odd formats models produce. The recordings need refreshing when the prompt or model changes.

7Conclusion

In this answer, we separated the service's own code from the model. A fake ChatModel behind a real ChatClient let us unit test parsing, fallbacks and the request flow on every commit, and prompt construction and output parsing were tested on their own. Against the real model, we ran a fixed dataset of tickets with expected facts in a scheduled job, asserted properties such as key facts, valid JSON and length instead of exact text, and judged the run by a pass rate tracked over time.

What to say in the interviewAbout 90 seconds aloud

Open with

I would split the tests into the code I own and the model's behaviour. For the code I own, I write a small fake ChatModel that records the Prompt it receives and returns a fixed ChatResponse, and I build a real ChatClient on top of it with ChatClient.builder(fake).

Then, if they want more

Then the unit tests run the real request building and entity conversion without any network, and I can check that the prompt contains the ticket text, that valid JSON becomes the right record, and that malformed answers, like a sentence instead of JSON, lead to the fallback. Mocking ChatModel with Mockito works too.

I also pull prompt construction and output parsing into their own classes and test them directly, for example truncation of long tickets and masking of card numbers. All of that runs on every commit in milliseconds. For the model itself, I keep a fixed dataset of thirty to fifty anonymised tickets with the expected category and key facts.

A separate test class, tagged so the normal build skips it, runs them against the real model nightly and whenever the prompt or model changes. Because outputs vary, it asserts properties, valid JSON, right category, contains the key facts, under a length limit, and it passes if around ninety percent of tickets pass, with results tracked over time.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
Spring AI reference
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "How would you write automated tests for a Spring Boot service that uses ChatClient to...": https://scrivio-interview-library.netlify.app/spring-boot/spring-ai/a8493bc6fb/