Spring / Spring AI interview questions
How do you test Spring AI components without calling real AI APIs?
Testing AI-integrated code without hitting real provider APIs is important for cost control, speed, and determinism. Spring AI provides two main strategies: using a MockChatModel / test double, or using the auto-configured @SpringBootTest with a property override that points to a local server or stub.
1. MockChatModel — Spring AI ships a MockChatModel that you can configure with fixed responses. Suitable for unit tests of service logic.
@Test void shouldReturnSummary() { // Arrange ChatModel mock = new MockChatModel( new ChatResponse(List.of( new Generation(new AssistantMessage("This is a test summary."))))); ChatClient client = ChatClient.builder(mock).build(); // Act String result = new SummaryService(client).summarise("some text"); // Assert assertThat(result).isEqualTo("This is a test summary."); }
2. WireMock / local stub server — For integration tests that need to exercise the full HTTP stack (retries, serialization, timeouts), point Spring AI at a WireMock server that returns realistic provider JSON.
# test application.properties spring.ai.openai.base-url=http://localhost:${wiremock.server.port} spring.ai.openai.api-key=test-key
3. Ollama with a small model — For end-to-end tests in a CI environment, run a containerised Ollama instance (via Testcontainers) with a small model like phi3:mini. Response quality is lower but the full call path is exercised.
More Related questions...