/langchain4j-testing-strategies
Provides unit test, integration test, and mock AI patterns for LangChain4j applications. Creates mock LLM responses, tests retrieval chains, validates RAG workflows, and implements Testcontainers-based integration tests for Java AI services. Use when unit testing AI services,
$ npx -y skills add giuseppe-trisciuoglio/developer-kit --skill langchain4j-testing-strategies --agent claude-codeHow it fires
How this skill gets triggered: by you, by Claude, or both.
- Fires itselfAuto-invocation. Claude auto-loads it when your prompt matches the work.
- You can call itInvoke it directly when you want it.
- Slash command
/langchain4j-testing-strategies
Context preview
The summary Claude sees to decide when to auto-load this skill.
Provides unit test, integration test, and mock AI patterns for LangChain4j applications. Creates mock LLM responses, tests retrieval chains, validates RAG workflows, and implements Testcontainers-based integration tests for Java AI services. Use when unit testing AI services,
SKILL.md
langchain4j-testing-strategies.SKILL.mdname: langchain4j-testing-strategies
description: Provides unit test, integration test, and mock AI patterns for LangChain4j applications. Creates mock LLM responses, tests retrieval chains, validates RAG workflows, and implements Testcontainers-based integration tests for Java AI services. Use when unit testing AI services, integration testing LangChain4j components, mocking AI models, or testing LLM-based Java applications.
allowed-tools: Read, Write, Edit, Bash, Glob, Grep
LangChain4J Testing Strategies
Overview
Patterns for unit testing with mocks, integration testing with Testcontainers, and end-to-end validation of RAG systems, AI Services, and tool execution.
When to Use
- **Unit testing AI services**: When you need fast, isolated tests for services using LangChain4j AiServices
- **Integration testing LangChain4j components**: When testing real ChatModel, EmbeddingModel, or RAG pipelines with Testcontainers
- **Mocking AI models**: When you need deterministic responses without calling external APIs
- **Testing LLM-based Java applications**: When validating RAG workflows, tool execution, or retrieval chains
Instructions
1. Unit Testing with Mocks
Use mock models for fast, isolated testing. See `references/unit-testing.md`.
ChatModel mockModel = mock(ChatModel.class);
when(mockModel.generate(any(String.class)))
.thenReturn(Response.from(AiMessage.from("Mocked response")));
var service = AiServices.builder(AiService.class)
.chatModel(mockModel)
.build();2. Configure Testing Dependencies
Setup Maven/Gradle dependencies. See `references/testing-dependencies.md`.
- `langchain4j-test` - Guardrail assertions
- `testcontainers` - Containerized testing
- `mockito` - Mock external dependencies
- `assertj` - Fluent assertions
3. Integration Testing with Testcontainers
Test with real services. See `references/integration-testing.md`.
@Testcontainers
class OllamaIntegrationTest {
@Container
static GenericContainer<?> ollama = new GenericContainer<>(
DockerImageName.parse("ollama/ollama:0.5.4")
).withExposedPorts(11434);
@Test
void shouldGenerateResponse() {
// Verify container is healthy
assertTrue(ollama.isRunning());
await().atMost(30, TimeUnit.SECONDS)
.until(() -> ollama.getLogs().contains("API server listening"));
ChatModel model = OllamaChatModel.builder()
.baseUrl(ollama.getEndpoint())
.build();
// Verify model responds before running tests
assertDoesNotThrow(() -> model.generate("ping"));
String response = model.generate("Test query");
assertNotNull(response);
}
}4. Advanced Features
Streaming, memory, error handling patterns in `references/advanced-testing.md`.
5. Testing Workflow
Follow the testing pyramid from `references/workflow-patterns.md`:
- **70% Unit Tests**: Fast, isolated with mocks
- **20% Integration Tests**: Real services with health checks
- **10% End-to-End Tests**: Complete workflows
70% Unit Tests ─ Mock ChatModel, guardrails, edge cases
20% Integration Tests ─ Testcontainers, vector stores, RAG
10% End-to-End Tests ─ Complete user journeys
Troubleshooting
- **Container fails to start**: Check Docker daemon is running, verify image exists, increase timeout
- **Model not responding**: Verify baseUrl is correct, check container logs, ensure model is loaded
- **Test timeout**: Increase `@Timeout` duration for slow models, check container resource limits
- **Flaky tests**: Add retry logic or health checks before assertions
Examples
Unit Test
@Test
void shouldProcessQueryWithMock() {
ChatModel mockModel = mock(ChatModel.class);
when(mockModel.generate(any(String.class)))
.thenReturn(Response.from(AiMessage.from("Test response")));
var service = AiServices.builder(AiService.class)
.chatModel(mockModel)
.build();
String result = service.chat("What is Java?");
assertEquals("Test response", result);
}Integration Test with Testcontainers
@Testcontainers
class RAGIntegrationTest {
@Container
static GenericContainer<?> ollama = new GenericContainer<>(
DockerImageName.parse("ollama/ollama:0.5.4")
);
@BeforeAll
static void waitForContainerReady() {
await().atMost(60, TimeUnit.SECONDS)
.until(() -> ollama.getLogs().contains("API server listening"));
}
@Test
void shouldCompleteRAGWorkflow() {
assertTrue(ollama.isRunning());
var chatModel = OllamaChatModel.builder()
.baseUrl(ollama.getEndpoint())
.build();
var embeddingModel = OllamaEmbeddingModel.builder()
.baseUrl(ollama.getEndpoint())
.build();
var store = new InMemoryEmbeddingStore<>();
var retriever = EmbeddingStoreContentRetriever.builder()
.chatModel(chatModel)
.embeddingStore(store)
.embeddingModel(embeddingModel)
.build();
var assistant = AiServices.builder(RagAssistant.class)
.chatLanguageModel(chatModel)
.contentRetriever(retriever)
.build();
String response = assistant.chat("What is Spring Boot?");
assertNotNull(response);
assertTrue(response.contains("Spring"));
}
}Best Practices
- Use `@BeforeEach`/`@AfterEach` for test isolation
- Never call real APIs in unit tests; use mocks
- Include `@Timeout` for external service calls
- Test both success and error handling scenarios
- Validate response coherence and edge cases
Common Patterns
Mock Strategy
ChatModel mockModel = mock(ChatModel.class);
when(mockModel.generate(anyString())).thenReturn(Response.from(AiMessage.from("Mocked")));
when(mockModel.generate(eq("Hello"))).thenReturn(RespoRead more
name: langchain4j-testing-strategies description: Provides unit test, integration test, and mock AI patterns for LangChain4j applications. Creates mock LLM responses, tests retrieval chains, validates RAG workflows, and implements Testcontainers-based integration tests for Java AI services. Use when unit testing AI services, integration testing LangChain4j components, mocking AI models, or testing LLM-based Java applications. allowed-tools: Read, Write, Edit, Bash, Glob, Grep
LangChain4J Testing Strategies
Overview
Patterns for unit testing with mocks, integration testing with Testcontainers, and end-to-end validation of RAG systems, AI Services, and tool execution.
When to Use
- **Unit testing AI services**: When you need fast, isolated tests for services using LangChain4j AiServices
- **Integration testing LangChain4j components**: When testing real ChatModel, EmbeddingModel, or RAG pipelines with Testcontainers
- **Mocking AI models**: When you need deterministic responses without calling external APIs
- **Testing LLM-based Java applications**: When validating RAG workflows, tool execution, or retrieval chains
Instructions
1. Unit Testing with Mocks
Use mock models for fast, isolated testing. See `references/unit-testing.md`.
ChatModel mockModel = mock(ChatModel.class);
when(mockModel.generate(any(String.class)))
.thenReturn(Response.from(AiMessage.from("Mocked response")));
var service = AiServices.builder(AiService.class)
.chatModel(mockModel)
.build();2. Configure Testing Dependencies
Setup Maven/Gradle dependencies. See `references/testing-dependencies.md`.
- `langchain4j-test` - Guardrail assertions
- `testcontainers` - Containerized testing
- `mockito` - Mock external dependencies
- `assertj` - Fluent assertions
3. Integration Testing with Testcontainers
Test with real services. See `references/integration-testing.md`.
@Testcontainers
class OllamaIntegrationTest {
@Container
static GenericContainer<?> ollama = new GenericContainer<>(
DockerImageName.parse("ollama/ollama:0.5.4")
).withExposedPorts(11434);
@Test
void shouldGenerateResponse() {
// Verify container is healthy
assertTrue(ollama.isRunning());
await().atMost(30, TimeUnit.SECONDS)
.until(() -> ollama.getLogs().contains("API server listening"));
ChatModel model = OllamaChatModel.builder()
.baseUrl(ollama.getEndpoint())
.build();
// Verify model responds before running tests
assertDoesNotThrow(() -> model.generate("ping"));
String response = model.generate("Test query");
assertNotNull(response);
}
}4. Advanced Features
Streaming, memory, error handling patterns in `references/advanced-testing.md`.
5. Testing Workflow
Follow the testing pyramid from `references/workflow-patterns.md`:
- **70% Unit Tests**: Fast, isolated with mocks
- **20% Integration Tests**: Real services with health checks
- **10% End-to-End Tests**: Complete workflows
70% Unit Tests ─ Mock ChatModel, guardrails, edge cases 20% Integration Tests ─ Testcontainers, vector stores, RAG 10% End-to-End Tests ─ Complete user journeys
Troubleshooting
- **Container fails to start**: Check Docker daemon is running, verify image exists, increase timeout
- **Model not responding**: Verify baseUrl is correct, check container logs, ensure model is loaded
- **Test timeout**: Increase `@Timeout` duration for slow models, check container resource limits
- **Flaky tests**: Add retry logic or health checks before assertions
Examples
Unit Test
@Test
void shouldProcessQueryWithMock() {
ChatModel mockModel = mock(ChatModel.class);
when(mockModel.generate(any(String.class)))
.thenReturn(Response.from(AiMessage.from("Test response")));
var service = AiServices.builder(AiService.class)
.chatModel(mockModel)
.build();
String result = service.chat("What is Java?");
assertEquals("Test response", result);
}Integration Test with Testcontainers
@Testcontainers
class RAGIntegrationTest {
@Container
static GenericContainer<?> ollama = new GenericContainer<>(
DockerImageName.parse("ollama/ollama:0.5.4")
);
@BeforeAll
static void waitForContainerReady() {
await().atMost(60, TimeUnit.SECONDS)
.until(() -> ollama.getLogs().contains("API server listening"));
}
@Test
void shouldCompleteRAGWorkflow() {
assertTrue(ollama.isRunning());
var chatModel = OllamaChatModel.builder()
.baseUrl(ollama.getEndpoint())
.build();
var embeddingModel = OllamaEmbeddingModel.builder()
.baseUrl(ollama.getEndpoint())
.build();
var store = new InMemoryEmbeddingStore<>();
var retriever = EmbeddingStoreContentRetriever.builder()
.chatModel(chatModel)
.embeddingStore(store)
.embeddingModel(embeddingModel)
.build();
var assistant = AiServices.builder(RagAssistant.class)
.chatLanguageModel(chatModel)
.contentRetriever(retriever)
.build();
String response = assistant.chat("What is Spring Boot?");
assertNotNull(response);
assertTrue(response.contains("Spring"));
}
}Best Practices
- Use `@BeforeEach`/`@AfterEach` for test isolation
- Never call real APIs in unit tests; use mocks
- Include `@Timeout` for external service calls
- Test both success and error handling scenarios
- Validate response coherence and edge cases
Common Patterns
Mock Strategy
ChatModel mockModel = mock(ChatModel.class);
when(mockModel.generate(anyString())).thenReturn(Response.from(AiMessage.from("Mocked")));
when(mockModel.generate(eq("Hello"))).thenReturn(RespoShowing the first part of this file.
Modular plugin marketplace for Claude Code and agentic CLIs, with validated, spec-driven skills, agents, commands, and workflows for Java, TypeScript, Python, PHP, AWS, and AI.
Repo: giuseppe-trisciuoglio/developer-kit
Other skills on developer-kit.
- /chunking-strategy
Provides chunking strategies for RAG systems. Generates chunk size recommendations (256-1024 tokens), overlap percentages (10-20%), and semantic boundary detection methods. Validates semantic coherence and evaluates retrieval precision/recall metrics. Use when building
Open skill - /prompt-engineering
Provides workflows to write, debug, and optimize prompts for LLMs, including few-shot example selection, chain-of-thought structuring, system prompt design, and template composition. Use when the user asks to write or improve a prompt, wants help with few-shot examples,
Open skill - /rag
Implements document chunking, embedding generation, vector storage, and retrieval pipelines for Retrieval-Augmented Generation systems. Use when building RAG applications, creating document Q&A systems, or integrating AI with knowledge bases.
Open skill - /aws-cloudformation-auto-scaling
Provides AWS CloudFormation patterns for Auto Scaling including EC2, ECS, and Lambda. Use when creating Auto Scaling groups, launch configurations, launch templates, scaling policies, lifecycle hooks, and predictive scaling. Covers template structure with Parameters, Outputs,
Open skill - /aws-cloudformation-bedrock
Provides AWS CloudFormation patterns for Amazon Bedrock resources including agents, knowledge bases, data sources, guardrails, prompts, flows, and inference profiles. Use when creating Bedrock agents with action groups, implementing RAG with knowledge bases, configuring vector
Open skill - /aws-cloudformation-cloudfront
Provides AWS CloudFormation patterns for CloudFront distributions, origins (ALB, S3, Lambda@Edge, VPC Origins), CacheBehaviors, Functions, SecurityHeaders, parameters, Outputs and cross-stack references. Use when creating CloudFront distributions with CloudFormation, configuring
Open skill

