PluginBench
Skill
Pass
Audit score 90

langchain4j-testing-strategies

giuseppe-trisciuoglio/developer-kit

Unit, integration, and mock testing patterns for LangChain4j Java AI services and RAG workflows.

What is langchain4j-testing-strategies?

Provides testing strategies for LangChain4j applications including mock LLM responses, Testcontainers-based integration tests, and RAG validation. Use when unit testing AI services, mocking models, or integration testing LangChain4j components with real services.

  • Mock ChatModel and EmbeddingModel responses for fast, isolated unit tests
  • Integration testing with Testcontainers for real LangChain4j services and RAG pipelines
  • Test retrieval chains, embedding stores, and content retrievers
  • Validate complete RAG workflows and AI service behavior
  • Implement health checks and container readiness verification
  • Support streaming, memory, and error handling test patterns

How to install langchain4j-testing-strategies

npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit --skill langchain4j-testing-strategies
Prerequisites
  • Maven or Gradle project with LangChain4j dependencies
  • Docker daemon running for Testcontainers-based integration tests
  • langchain4j-test, testcontainers, mockito, and assertj libraries configured
Claude Code
Cursor
Windsurf
Cline

How to use langchain4j-testing-strategies

  1. 1.Add testing dependencies (langchain4j-test, testcontainers, mockito, assertj) to Maven/Gradle
  2. 2.Create unit tests using mock(ChatModel.class) and when/thenReturn for deterministic responses
  3. 3.Configure Testcontainers with @Testcontainers and @Container annotations for integration tests
  4. 4.Add health checks and await() conditions to verify container readiness before assertions
  5. 5.Implement RAG integration tests with real EmbeddingModel and InMemoryEmbeddingStore
  6. 6.Follow the testing pyramid: 70% unit tests with mocks, 20% integration tests, 10% end-to-end tests

Use cases

Good for
  • Unit testing AiServices with mocked ChatModel responses for deterministic results
  • Integration testing RAG systems with containerized Ollama or other LLMs
  • Validating retrieval chains and embedding store functionality
  • Testing tool execution and LLM-based Java applications without external API calls
  • End-to-end workflow validation with complete AI service pipelines
Who it's for
  • Java developers building LangChain4j applications
  • QA engineers testing AI services and RAG systems
  • Backend engineers validating LLM integrations
  • Teams needing fast, isolated unit tests for AI components

langchain4j-testing-strategies FAQ

When should I use mocks vs. Testcontainers?

Use mocks for unit tests requiring fast, isolated execution without external dependencies. Use Testcontainers for integration tests validating real ChatModel, EmbeddingModel, or RAG pipeline behavior with actual services.

How do I handle non-deterministic AI responses in tests?

Mock the ChatModel with specific when/thenReturn conditions for unit tests. For integration tests, validate response properties (non-null, contains keywords) rather than exact matches, or use deterministic models like Ollama with fixed seeds.

What should I do if my Testcontainers test times out?

Verify Docker daemon is running, increase @Timeout duration, add await() health checks before assertions, check container logs for startup errors, and ensure sufficient system resources for the container.

Can I test RAG workflows without real embedding models?

Yes, use InMemoryEmbeddingStore with mocked EmbeddingModel for unit tests. For realistic validation, use Testcontainers with Ollama or another containerized embedding service.

Should I call real APIs in my tests?

No. Always use mocks in unit tests to avoid costs, rate limiting, and flakiness. Reserve real API calls for integration tests with Testcontainers or separate end-to-end test suites.

Full instructions (SKILL.md)

Source of truth, from giuseppe-trisciuoglio/developer-kit.


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(Response.from(AiMessage.from("Hi")));
when(mockModel.generate(contains("Java"))).thenReturn(Response.from(AiMessage.from("Java")));

Assertion Helpers

assertThat(response).isNotNull().isNotEmpty();
assertThat(response).containsAll(expectedKeywords);
assertThat(response).doesNotContain("error");

Reference Documentation

Constraints and Warnings

  • AI responses are non-deterministic; use mocks for reliable unit tests
  • Avoid real API calls in tests to prevent costs and rate limiting
  • Integration tests require Docker; use container health checks
  • RAG tests need properly seeded embedding stores
  • Mock-based tests cannot guarantee actual LLM behavior; supplement with integration tests
  • Use test-specific configuration profiles; never affect production data

Related skills

More from giuseppe-trisciuoglio/developer-kit and the wider catalog.

LAlangchain4j-tool-function-calling-patterns logo

langchain4j-tool-function-calling-patterns

giuseppe-trisciuoglio/developer-kit

Annotate Java methods as LLM-callable tools, register with AiServices, and handle execution errors in LangChain4j agents.

1.4k installs
LAlangchain4j-vector-stores-configuration logo

langchain4j-vector-stores-configuration

giuseppe-trisciuoglio/developer-kit

Configure LangChain4J vector stores for RAG applications with PostgreSQL, Pinecone, MongoDB, Milvus, and Neo4j.

1.4k installsAudited
LElearn logo

learn

giuseppe-trisciuoglio/developer-kit

Provides autonomous project pattern learning by analyzing the codebase to discover development conventions, architectural patterns, and coding standards, then generates project rule files in .claude/rules/. Use when user asks to "learn from project", "extract project rules", "analyze codebase conventions", "discover project patterns", or wants to auto-generate Claude Code rules for the current project.

953 installsAudited
MEmemory-md-management logo

memory-md-management

giuseppe-trisciuoglio/developer-kit

Provides comprehensive memory file management capabilities including auditing, quality assessment, and targeted improvements for files such as CLAUDE.md. Use when user asks to check, audit, update, improve, fix, maintain, or validate project memory files. Also triggers for "project memory optimization", "CLAUDE.md quality check", "documentation review", or when a project memory file needs to be created from scratch. This skill scans memory files, evaluates quality against standardized criteria, outputs detailed quality reports with scores and recommendations, then makes targeted updates with user approval.

1.1k installsAudited
NEnestjs logo

nestjs

giuseppe-trisciuoglio/developer-kit

NestJS framework patterns with Drizzle ORM for building scalable REST/GraphQL APIs and microservices.

1.8k installs
NEnestjs-best-practices logo

nestjs-best-practices

giuseppe-trisciuoglio/developer-kit

Provides comprehensive NestJS best practices including modular architecture, dependency injection scoping, exception filters, DTO validation with class-validator, and Drizzle ORM integration. Use when designing NestJS modules, implementing providers, creating exception filters, validating DTOs, or integrating Drizzle ORM within NestJS applications.

1.2k installsAudited