ferroxlabs/wayland/java-testing-patterns

Claude Code and agent skill by ferroxlabs/wayland

Trust tier 3
  • community
  • ext:[{"type":"hook","description":"Pre/post lifecycle hooks"}]
Source check pending

Checking that the SKILL.md file is still in the repository.

Guides expert-level Java testing: JUnit 5, Mockito, AssertJ, Testcontainers, parameterized tests, and Spring Boot test slices. Use when the user asks about Java testing, JUnit 5, Mockito, AssertJ, Testcontainers, parameterized tests, Spring Boot testing. Do NOT use when the user asks about Java project setup (use `java-project-setup`), Java Spring patterns (use `java-spring-patterns`), general testing concepts (use `unit-testing-patterns`).

Install

npx vskill@latest install ferroxlabs/wayland/java-testing-patterns

Semi-extensibleMentions customization, but needs skill-specific knowledge. Read the extensible skills standard

SKILL.md

The same SKILL.md was published earlier as ferroxlabs/wayland/java-testing-patterns.

Java Testing Patterns

When to Use

Use this skill when:

  • The user asks how to write unit tests for a Java class, method, or service using JUnit 5 annotations and lifecycle hooks
  • The user asks how to mock dependencies in Java using Mockito, including argument captors, stubbing, and verification
  • The user asks how to write fluent assertions with AssertJ, including soft assertions and custom assertion classes
  • The user asks how to test database interactions, message queues, or HTTP APIs using Testcontainers with real infrastructure
  • The user asks how to write parameterized tests with @ParameterizedTest, @CsvSource, @MethodSource, or @EnumSource
  • The user asks how to test Spring Boot applications using test slices like @WebMvcTest, @DataJpaTest, or @SpringBootTest
  • The user asks about test isolation, fixture design, shared state management, or test lifecycle management in Java
  • The user asks about coverage configuration with JaCoCo, mutation testing with PIT, or organizing test source sets in Maven or Gradle

Do NOT use this skill when:

  • The user asks about setting up a Java project from scratch -- use java-project-setup instead
  • The user asks about Spring dependency injection patterns, AOP, or application context configuration outside of testing -- use java-spring-patterns instead
  • The user asks about general testing theory, TDD philosophy, or testing vocabulary without a Java-specific context -- use unit-testing-patterns instead
  • The user asks about performance benchmarking in Java -- JMH benchmarks have their own conventions that are out of scope here
  • The user asks about contract testing with Pact or consumer-driven contracts -- that requires its own dedicated skill

Process

1. Identify the Test Scope and Layer

Before writing any test code, determine the exact type of test being written. Each layer has a different cost, speed, and isolation profile.

  • Unit test: Tests a single class or method with all external dependencies replaced by mocks or stubs. Runs in milliseconds. No Spring context. No I/O.
  • Integration test: Wires together 2-5 real collaborators with mocks at the boundary (e.g., real service + real repository but mocked HTTP client). May start a partial Spring context.
  • Slice test: Uses a Spring Boot test slice annotation to load only the relevant application layer. @WebMvcTest loads MVC components only; @DataJpaTest loads JPA repositories and an embedded H2 or Testcontainers database only.
  • System / end-to-end test: Full Spring Boot application context with real infrastructure via Testcontainers. Slow but high-confidence. Reserve for critical paths only.
  • Apply the test pyramid: aim for roughly 70% unit, 20% integration/slice, 10% system tests by count.
  • Confirm the project uses JUnit 5 (JUnit Jupiter), not JUnit 4. Key indicator: @Test is from org.junit.jupiter.api, not org.junit.
2. Configure the Test Infrastructure

Set up the correct test dependencies and ensure the test runner is properly configured before writing any tests.

  • In Maven, the spring-boot-starter-test dependency transitively provides: JUnit 5, Mockito 5, AssertJ 3, Hamcrest 2, JSONAssert, JsonPath, and Awaitility. Confirm this is present in pom.xml with scope=test.
  • In Gradle, this is testImplementation 'org.springframework.boot:spring-boot-starter-test'. Confirm useJUnitPlatform() is set in the test task block -- without it, JUnit 5 tests silently pass with zero executions.
  • Add Testcontainers BOM (org.testcontainers:testcontainers-bom) to dependency management to keep module versions aligned. Add org.testcontainers:junit-jupiter and the specific module (e.g., org.testcontainers:postgresql).
  • Add JaCoCo plugin for coverage. Configure minimum line coverage of 80% and branch coverage of 70% as CI gates. Exclude generated code: DTOs produced by MapStruct, Lombok-generated classes, and Spring-generated proxy classes.
  • For mutation testing with PIT (pitest-maven-plugin), configure targetClasses to include only your own packages, and set mutationThreshold to 60% as a starting baseline.
  • Enable the Surefire plugin (Maven) or the test task (Gradle) to run JUnit 5 platform. Surefire 2.22.0+ supports JUnit 5 natively.
3. Design the Test Class Structure

A well-structured test class is as readable as a specification document. Apply these conventions consistently.

  • Name the test class ClassUnderTestTest for unit tests (e.g., OrderServiceTest). For integration tests, use ClassUnderTestIT (the IT suffix is picked up by Maven Failsafe automatically).
  • Use @DisplayName at the class level to describe the system under test: @DisplayName("OrderService -- business logic for order lifecycle").
  • Group related tests using @Nested inner classes. Each @Nested class should represent one distinct scenario cluster: e.g., class WhenOrderIsEmpty, class WhenOrderExceedsInventory. Apply @DisplayName to each nested class.
  • Declare the class under test as a field. For classes with no Spring context, instantiate it directly in @BeforeEach. Never use @SpringBootTest for a class that can be tested without a Spring context -- it adds 3-30 seconds of startup time.
  • Use @BeforeEach for cheap per-test setup (creating instances, resetting mocks). Use @BeforeAll (static) only for genuinely expensive, read-only setup like loading a large fixture file or starting a Testcontainer that is safe to share across all tests in the class.
  • Use @AfterEach for cleanup only when a test modifies shared state (e.g., a static cache, a file on disk). Prefer designing tests so cleanup is not needed.
4. Write Assertions with AssertJ

AssertJ provides a fluent, readable, and type-safe alternative to JUnit's built-in Assertions. It produces superior failure messages.

  • Always static-import org.assertj.core.api.Assertions.assertThat (and assertThatThrownBy, assertThatCode, catchThrowableOfType).
  • Chain assertions: assertThat(result).isNotNull().hasSize(3).containsExactlyInAnyOrder("A", "B", "C"). This reads like a sentence and provides a precise failure message.
  • For exception testing, use assertThatThrownBy(() -> service.process(null)).isInstanceOf(IllegalArgumentException.class).hasMessage("Input must not be null"). Never use @Test(expected = ...) (JUnit 4 pattern) or assertThrows when you need to assert the exception message -- assertThatThrownBy chains are cleaner.
  • For multiple assertions that should all run even if one fails, use SoftAssertions: SoftAssertions.assertSoftly(soft -> { soft.assertThat(order.status()).isEqualTo(CONFIRMED); soft.assertThat(order.total()).isEqualByComparingTo("99.99"); }). This is essential for validating DTOs with multiple fields.
  • For floating-point and BigDecimal comparisons, use isEqualByComparingTo("9.99") rather than isEqualTo -- isEqualTo on BigDecimal considers 9.90 and 9.9 unequal due to scale.
  • Use usingRecursiveComparison() to compare complex objects field-by-field without implementing equals(): assertThat(actual).usingRecursiveComparison().ignoringFields("id", "createdAt").isEqualTo(expected).
5. Apply Mockito for Dependency Isolation

Mockito is the standard Java mocking library. Use it precisely -- over-mocking is as harmful as under-mocking.

  • Annotate the test class with @ExtendWith(MockitoExtension.class) (JUnit 5 integration). This initializes @Mock and @InjectMocks fields automatically and verifies all stubbing usage after each test (strict stubbing is enabled by default in Mockito 3+).
  • Declare mocks with @Mock on the field. Declare the class under test with @InjectMocks -- Mockito will inject mocks via constructor, setter, or field injection (constructor injection is preferred and most reliable).
  • Stub with when(mock.method(arg)).thenReturn(value) for simple returns. Use thenThrow(new RuntimeException()) to simulate failures. Use thenAnswer(invocation -> ...) when the return value must depend on the input argument.
  • Use ArgumentCaptor to verify what arguments were passed to a mock: declare @Captor ArgumentCaptor<EmailRequest> captor, then verify(emailService).send(captor.capture()), then assertThat(captor.getValue().recipient()).isEqualTo("user@example.com").
  • Use verify(mock, times(1)).method(arg) for exact invocation counts. Use verify(mock, never()).method(any()) to assert a code path was not taken. Use verifyNoMoreInteractions(mock) sparingly -- it makes tests brittle when adding new functionality.
  • Do NOT mock: value objects, DTOs, domain entities with no dependencies, String, List, Optional, or any class you own that is cheap to instantiate. Mocking your own simple classes breaks tests when behavior changes and reveals nothing about correctness.
  • Use @Spy only when you need to partially mock a real object, typically when testing a class that calls its own overridable methods. Prefer refactoring to avoid the need for spies.
6. Write Parameterized Tests

Parameterized tests eliminate copy-paste test duplication and make boundary conditions explicit.

  • Annotate with @ParameterizedTest instead of @Test. Always pair with a source annotation.
  • Use @CsvSource for simple inline data with 2-5 inputs and 1 expected output: @CsvSource({"0, EMPTY", "1, SINGLE", "100, BULK"}). The first line can be a header if you use useHeadersInDisplayName = true.
  • Use @MethodSource("provideInvalidInputs") for complex objects, collections, or when setup logic is needed. The provider method must be static, return a Stream<Arguments>, and live in the same class (or a separate utility class referenced as "com.example.TestData#provideInvalidInputs").
  • Use @EnumSource(value = OrderStatus.class, names = {"CANCELLED", "REFUNDED"}) to run a test for a subset of enum values.
  • Use @ValueSource(strings = {"", " ", "\t"}) to test boundary values for a single parameter type.
  • Name parameterized test methods to include the parameter in the display: @ParameterizedTest(name = "order with {0} items has status {1}"). This produces readable test reports.
  • Do NOT use @CsvSource for more than 6-7 rows -- move to @CsvFileSource with a .csv file in src/test/resources, or use @MethodSource with a clearly named factory method.
7. Use Testcontainers for Infrastructure Dependencies

Testcontainers provides disposable, real Docker containers for databases, message brokers, and HTTP services. It eliminates the "works on my machine" problem.

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 95 of 100Pattern checks on the skill's files.
  • Model reviewPassed

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

7-day trend score
5

Not refreshed yet.

Extension points

  • hookPre/post lifecycle hooks

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/ferroxlabs/wayland/java-testing-patterns/badge)](https://verified-skill.com/skills/ferroxlabs/wayland/java-testing-patterns)

Something wrong with this skill or its page? Tell us.