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-key3. 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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
