Skip to main content

Testing

An application built on a large language model (LLM) is harder to test than ordinary code:

  • the model can answer the same question differently each time;
  • calling the model takes time and costs money;
  • whether an answer is right is often a question of meaning, not of exact text.

This page shows how to test such an application with JUnit and AssertJ, using the langchain4j-test module:

  • Unit tests without a model: replace the model with a mock that answers what the test tells it to. These tests are fast, free and give the same result every time.
  • Checking what an AI Service did: which tools it executed, with which arguments, which sources it retrieved, how often it called the model and how it ended.
  • Judging answers with a model: check what cannot be checked exactly, such as "says that the booking cannot be found", with a model as the judge.
  • Tests with a real model: where they fit next to the fast tests, and what a single run can tell you.

Start with checks that do not need a model to judge the answer, such as which tool was executed: they are cheap and exact. Use a judge only for what they cannot check.

Testing or evaluation?

Testing and evaluation answer different questions:

  • Testing checks that your code works: while you develop and on every build, mostly with mocks and a few cases you write, with a pass or fail result. Most tests are fast and cheap, and testing is useful from the first day of a project. This page is about testing.
  • Evaluation measures how good the answers of your application are: with the real model, on many realistic inputs, often from real use, with scores that you compare over time. See Evaluation.
note

langchain4j-test is experimental: its API may change in future releases.

Setup​

Add langchain4j-test to your test dependencies. Its version comes from the langchain4j-bom:

<dependencyManagement>
<dependencies>
<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-bom</artifactId>
<version>1.24.1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

<dependencies>
<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

Without the BOM, note that langchain4j-test has a beta version: 1.24.1-beta34 goes with LangChain4j 1.24.1. The examples also use JUnit and the langchain4j module, which provides AI Services.

All assertions on this page, including the AssertJ ones, come with a single static import:

import static dev.langchain4j.test.LangChain4jAssertions.assertThat;

The examples test this AI Service of a car rental company, which can cancel bookings with a tool:

interface Assistant {

@SystemMessage("You are a customer support agent of a car rental company.")
String chat(String userMessage);
}

class BookingTools {

private final Set<String> bookings;
private final Set<String> cancelledBookings = new HashSet<>();

BookingTools(String... bookingNumbers) {
this.bookings = Set.of(bookingNumbers);
}

@Tool("Cancels the booking with the given booking number")
String cancelBooking(String bookingNumber) {
if (!bookings.contains(bookingNumber)) {
throw ToolErrorVisibleToLlm.from("Booking " + bookingNumber + " not found");
}
cancelledBookings.add(bookingNumber);
return "Booking " + bookingNumber + " is cancelled";
}

boolean isCancelled(String bookingNumber) {
return cancelledBookings.contains(bookingNumber);
}
}

Unit tests without a model​

MockChatModel is a ChatModel for tests: it needs no network and answers the way the test tells it to. You script its answers step by step, one step per request:

import static dev.langchain4j.test.LangChain4jAssertions.assertThat;

import dev.langchain4j.service.AiServices;
import dev.langchain4j.test.mock.MockChatModel;
import java.util.Map;
import org.junit.jupiter.api.Test;

class AssistantTest {

@Test
void should_cancel_the_booking() {
MockChatModel model = MockChatModel.thatCallsTool("cancelBooking", Map.of("bookingNumber", "MS-777"))
.thenResponds("Your booking MS-777 is cancelled.");
BookingTools bookingTools = new BookingTools("MS-777");

Assistant assistant = AiServices.builder(Assistant.class)
.chatModel(model)
.tools(bookingTools)
.build();

String answer = assistant.chat("Please cancel my booking MS-777");

assertThat(bookingTools.isCancelled("MS-777")).isTrue();
assertThat(answer).isEqualTo("Your booking MS-777 is cancelled.");
}
}

Here is what happens:

  1. The AI Service sends the user message to the model.
  2. The mock answers with a call of the cancelBooking tool.
  3. The AI Service executes the tool and sends its result to the model in a second request.
  4. The mock answers with the text, which the AI Service returns.

The tool call and the answer are what the test scripted, so the test checks what your own code did with them: here, that the tool really cancelled the booking. A test like this checks your code around the model: how the AI Service is set up, what it sends to the model and what it does with the answers. It does not check that a real model calls the right tool or answers well: for that, run the checks of Checking what an AI Service did with a real model, and use a judge.

The AI Service passes the arguments of a tool call to the tool method's parameters with the same names, here bookingNumber. It knows these names only when your code is compiled with the -parameters option of javac (in Maven, <maven.compiler.parameters>true</maven.compiler.parameters>), or when you set them with @P(name = "bookingNumber") (see Parameter Name). Otherwise the tool does not get the argument, and only a check of the tool's effect, like isCancelled(...) above, notices it.

The rules of a script:

  • Every that... method creates a mock with its first step (a method that takes several messages creates one step per message), and every then... method adds a step.

  • Each step answers exactly one request. A request after the last step fails with an IllegalStateException that shows the request, so the test notices when your code calls the model more often than expected.

  • To answer every further request with the last step, end the script with thenRepeats(). A step that calls a tool cannot repeat.

    MockChatModel model = MockChatModel.thatResponds("Hello!").thenRepeats();
  • To test how your code handles a failing model, for example your retry or fallback logic, let a step fail with the kind of exception a model provider throws:

    MockChatModel flaky = MockChatModel.thatFails(new InternalServerException("Service unavailable"))
    .thenResponds("Hello!");
  • A step can compute its answer from the request, with thatResponds(Function<ChatRequest, AiMessage>). Followed by thenRepeats(), it answers every request this way, for example requests that arrive in parallel.

  • For an AI Service method that returns an object, let the mock answer with its JSON, for example MockChatModel.thatResponds("{\"bookingNumber\": \"MS-777\"}"). By default, the mock reports no capabilities, so the AI Service adds format instructions to the user message. To test the JSON schema response format instead, add withSupportedCapabilities(Capability.RESPONSE_FORMAT_JSON_SCHEMA).

A mock remembers which steps were taken and which requests it received, so create a new one for each test.

What the model received​

To check what your code sent to the model, use the requests the mock recorded. requests() returns all of them, request() the only one and lastRequest() the last one:

assertThat(model.requests().get(0))
.hasSystemMessageContaining("customer support agent")
.hasLastUserMessageContaining("MS-777")
.hasToolSpecification("cancelBooking");

Streaming​

MockStreamingChatModel does the same for a StreamingChatModel. Each step can stream its answer in parts:

interface StreamingAssistant {

@SystemMessage("You are a customer support agent of a car rental company.")
TokenStream chat(String userMessage);
}
@Test
void should_stream_the_answer() throws Exception {
MockStreamingChatModel model = MockStreamingChatModel.thatStreams("Your booking ", "MS-777 ", "is cancelled.");

StreamingAssistant assistant = AiServices.builder(StreamingAssistant.class)
.streamingChatModel(model)
.build();

List<String> tokens = new CopyOnWriteArrayList<>();
CompletableFuture<ChatResponse> response = new CompletableFuture<>();
assistant.chat("Please cancel my booking MS-777")
.onPartialResponse(tokens::add)
.onCompleteResponse(response::complete)
.onError(response::completeExceptionally)
.start();

assertThat(response.get(10, SECONDS).aiMessage().text()).isEqualTo("Your booking MS-777 is cancelled.");
assertThat(tokens).containsExactly("Your booking ", "MS-777 ", "is cancelled.");
}

To test how your code handles a stream that breaks off, let the stream fail after its first parts:

MockStreamingChatModel model = MockStreamingChatModel.thatStreams("Your booking ")
.andFails(new RuntimeException("Connection reset"));

Streaming and asynchronous methods shows a shorter way to test a streaming AI Service.

Other models​

There is a mock for each of these models. They all follow the same rules: that... and then... steps, thenRepeats(), thatFails(...), and the recorded requests().

MockReplacesExample
MockChatModelChatModelMockChatModel.thatResponds("Hello!")
MockStreamingChatModelStreamingChatModelMockStreamingChatModel.thatStreams("Hel", "lo!")
MockEmbeddingModelEmbeddingModelMockEmbeddingModel.thatEmbeds(0.1f, 0.2f, 0.3f).thenRepeats()
MockScoringModelScoringModelMockScoringModel.thatScores(0.9).thenRepeats()
MockModerationModelModerationModelMockModerationModel.thatDoesNotFlag().thenRepeats()
MockDecisionModelDecisionModelMockDecisionModel.thatAnswersYesNoQuestions(question -> 0.9).thenRepeats()

See the Javadoc of the mocks for all options.

Checking what an AI Service did​

The answer is only part of what an AI Service does: it may also execute tools, retrieve content and call the model several times. AiServiceCapture captures all of this while your code runs:

import static dev.langchain4j.test.service.AiServiceCapture.capture;
@Test
void should_cancel_the_booking() {
MockChatModel model = MockChatModel.thatCallsTool("cancelBooking", Map.of("bookingNumber", "MS-777"))
.thenResponds("Your booking MS-777 is cancelled.");

Assistant assistant = AiServices.builder(Assistant.class)
.chatModel(model)
.tools(new BookingTools("MS-777"))
.build();

AiServiceCapture capture = capture(() -> assistant.chat("Please cancel my booking MS-777"));

assertThat(capture)
.hasToolExecutedWith("cancelBooking", Map.of("bookingNumber", "MS-777"))
.hasNoFailedToolExecutions()
.hasOwnChatModelCallCount(2)
.toolExecutions()
.extracting(ToolExecution::result)
.containsExactly("Booking MS-777 is cancelled");
}

capture(...) works with every method of an AI Service created with AiServices, whatever it returns: capture.output() is what the AI Service produced, and capture.outputText() its text. These shortcuts, and assertThat(capture), need exactly one AI Service call in the lambda. When there are several, pick one with capture.invocation(Assistant.class) or capture.invocations().

hasToolExecutedWith(...) checks the arguments as the model sent them, not what the tool method received (see the -parameters note above): check that with the tool's result, as above, or with its effect.

These checks do not depend on how the model words its answer, so you can also run them with a real model, for example to check that the model calls the right tool. A real model may write an argument in several ways, such as MS-777 or ms-777: check such arguments with your own requirements:

assertThat(capture).hasToolExecutedWith("cancelBooking", arguments ->
assertThat((String) arguments.get("bookingNumber")).isEqualToIgnoringCase("MS-777"))