ferroxlabs/wayland/java-testing-patterns
Claude Code and agent skill by ferroxlabs/wayland
- community
- ext:[{"type":"hook","description":"Pre/post lifecycle hooks"}]
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-patternsSemi-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-setupinstead - The user asks about Spring dependency injection patterns, AOP, or application context configuration outside of testing -- use
java-spring-patternsinstead - The user asks about general testing theory, TDD philosophy, or testing vocabulary without a Java-specific context -- use
unit-testing-patternsinstead - 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.
@WebMvcTestloads MVC components only;@DataJpaTestloads 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:
@Testis fromorg.junit.jupiter.api, notorg.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-testdependency transitively provides: JUnit 5, Mockito 5, AssertJ 3, Hamcrest 2, JSONAssert, JsonPath, and Awaitility. Confirm this is present inpom.xmlwithscope=test. - In Gradle, this is
testImplementation 'org.springframework.boot:spring-boot-starter-test'. ConfirmuseJUnitPlatform()is set in thetesttask 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. Addorg.testcontainers:junit-jupiterand 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
targetClassesto include only your own packages, and setmutationThresholdto 60% as a starting baseline. - Enable the Surefire plugin (Maven) or the
testtask (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
ClassUnderTestTestfor unit tests (e.g.,OrderServiceTest). For integration tests, useClassUnderTestIT(the IT suffix is picked up by Maven Failsafe automatically). - Use
@DisplayNameat the class level to describe the system under test:@DisplayName("OrderService -- business logic for order lifecycle"). - Group related tests using
@Nestedinner classes. Each@Nestedclass should represent one distinct scenario cluster: e.g.,class WhenOrderIsEmpty,class WhenOrderExceedsInventory. Apply@DisplayNameto each nested class. - Declare the class under test as a field. For classes with no Spring context, instantiate it directly in
@BeforeEach. Never use@SpringBootTestfor a class that can be tested without a Spring context -- it adds 3-30 seconds of startup time. - Use
@BeforeEachfor 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
@AfterEachfor 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(andassertThatThrownBy,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) orassertThrowswhen you need to assert the exception message --assertThatThrownBychains 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
BigDecimalcomparisons, useisEqualByComparingTo("9.99")rather thanisEqualTo--isEqualToonBigDecimalconsiders9.90and9.9unequal due to scale. - Use
usingRecursiveComparison()to compare complex objects field-by-field without implementingequals():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@Mockand@InjectMocksfields automatically and verifies all stubbing usage after each test (strict stubbing is enabled by default in Mockito 3+). - Declare mocks with
@Mockon 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. UsethenThrow(new RuntimeException())to simulate failures. UsethenAnswer(invocation -> ...)when the return value must depend on the input argument. - Use
ArgumentCaptorto verify what arguments were passed to a mock: declare@Captor ArgumentCaptor<EmailRequest> captor, thenverify(emailService).send(captor.capture()), thenassertThat(captor.getValue().recipient()).isEqualTo("user@example.com"). - Use
verify(mock, times(1)).method(arg)for exact invocation counts. Useverify(mock, never()).method(any())to assert a code path was not taken. UseverifyNoMoreInteractions(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
@Spyonly 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
@ParameterizedTestinstead of@Test. Always pair with a source annotation. - Use
@CsvSourcefor 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 useuseHeadersInDisplayName = true. - Use
@MethodSource("provideInvalidInputs")for complex objects, collections, or when setup logic is needed. The provider method must bestatic, return aStream<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
@CsvSourcefor more than 6-7 rows -- move to@CsvFileSourcewith a.csvfile insrc/test/resources, or use@MethodSourcewith 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
- SKILL.md in the repositoryCheckingsrc/process/resources/skills-library/bodies/skills/software-engineering/java-testing-patterns/SKILL.md
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
[](https://verified-skill.com/skills/ferroxlabs/wayland/java-testing-patterns)