Skip to main content
skill CX Codex

junit-5-skill — Claude Code skill: Java test generation

Generates production-grade JUnit 5 unit tests for Java with assertions, parameterized tests, Mockito mocks, and nested test groups. Use it to quickly cover your Java code with tests.

MIT 289 installs ★ 393 updated 2026-10-13

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add LambdaTest/agent-skills --skill junit-5-skill -a claude-code
Open on GitHub

What junit-5-skill does

junit-5-skill creates JUnit 5 tests for Java projects. It covers standard unit tests with @Test and @DisplayName, parameterized tests via @ParameterizedTest with @CsvSource and @MethodSource, Spring integration tests, mocking with @Mock and @InjectMocks through Mockito, and nested test organization using @Nested. The skill activates when you mention JUnit, @Test, assertEquals, or "unit test Java".

You'll need test-scoped dependencies: junit-jupiter 5.11.0 and mockito-junit-jupiter 5.14.0 in your pom.xml or build.gradle. The skill generates examples for different scenarios — from basic assertEquals to assertThrows, assertAll, assertTimeout — and includes anti-patterns showing what not to do. Tests run via mvn test with filtering by class, method, or @Tag. The skill references a detailed playbook covering setup, lifecycle, parameterized tests, Mockito, nested groups, AssertJ, conditional annotations, custom extensions, CI/CD integration, debugging, and best practices.

What it helps with

  • write a basic unit test with assertions for a Java class
  • create a parameterized test that runs multiple data sets
  • mock service dependencies and verify they were called correctly
  • organize related tests into groups using @Nested
  • configure timeouts, conditional execution, or test repetition

Example prompts for the agent

  • Write a unit test for the Calculator class with add, subtract, and divide methods
  • Create a parameterized test using @CsvSource to validate user data
  • Cover UserService with tests that mock UserRepository and EmailService

How to install junit-5-skill

1Skills CLI (Vercel)

npx skills add LambdaTest/agent-skills --skill junit-5-skill -a claude-code

2Manually: put the files in place

~/.claude/skills/junit-5-skill/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/junit-5-skill/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about junit-5-skill

How do I install junit-5-skill in Claude Code?

Run two commands: npx skills add LambdaTest/agent-skills --skill junit-5-skill -a claude-code, then open ~/.claude/skills/junit-5-skill/SKILL.md to verify.

What does junit-5-skill do?

It generates production-grade JUnit 5 tests for Java with assertions, parameterized tests, Mockito mocks, nested test groups, and lifecycle hooks. It triggers when you mention JUnit, @Test, assertEquals, or "unit test Java".

What dependencies do I need for this skill to work?

Add junit-jupiter 5.11.0 and mockito-junit-jupiter 5.14.0 with test scope to your pom.xml or build.gradle. Without these, your tests won't compile.

Source text

SKILL.md · MIT
---
name: junit-5-skill
description: >
  Generates production-grade JUnit 5 unit and integration tests in Java.
  Covers assertions, parameterized tests, lifecycle hooks, mocking with
  Mockito, and nested tests. Use when user mentions "JUnit", "JUnit 5",
  "@Test", "assertEquals", "Assertions", "Java unit test". Triggers on:
  "JUnit", "@Test", "assertEquals", "Java test", "unit test Java".
languages:
  - Java
category: unit-testing
license: MIT
metadata:
  author: TestMu AI
  version: "1.0"
---

# JUnit 5 Testing Skill

You are a senior Java developer specializing in JUnit 5 testing.

## Step 1 — Test Type

```
├─ "unit test", "assert" → Standard unit test
├─ "parameterized", "multiple inputs" → @ParameterizedTest
├─ "mock", "Mockito" → Unit test with Mockito
├─ "integration test", "Spring" → Read reference/spring-integration.md
└─ Default → Standard unit test
```

## Core Patterns

### Basic Test

```java
import org.junit.jupiter.api.*;
import static org.junit.jupiter.api.Assertions.*;

class CalculatorTest {
    private Calculator calculator;

    @BeforeEach
    void setUp() {
        calculator = new Calculator();
    }

    @Test
    @DisplayName("Addition of two positive numbers")
    void addPositiveNumbers() {
        assertEquals(5, calculator.add(2, 3));
    }

    @Test
    void divideByZero_throwsException() {
        assertThrows(ArithmeticException.class, () -> calculator.divide(10, 0));
    }

    @Test
    void multipleAssertions() {
        assertAll("calculator operations",
            () -> assertEquals(4, calculator.add(2, 2)),
            () -> assertEquals(0, calculator.subtract(2, 2)),
            () -> assertEquals(6, calculator.multiply(2, 3))
        );
    }
}
```

### Assertions Reference

```java
assertEquals(expected, actual);
assertNotEquals(unexpected, actual);
assertTrue(condition);
assertFalse(condition);
assertNull(object);
assertNotNull(object);
assertThrows(IllegalArgumentException.class, () -> service.process(null));
assertTimeout(Duration.ofSeconds(2), () -> service.longRunningOp());
assertAll("group",
    () -> assertNotNull(user.getName()),
    () -> assertTrue(user.getAge() > 0)
);
assertIterableEquals(List.of(1, 2, 3), actualList);
```

### Parameterized Tests

```java
@ParameterizedTest
@ValueSource(strings = {"hello", "world", "junit"})
void stringIsNotEmpty(String value) {
    assertFalse(value.isEmpty());
}

@ParameterizedTest
@CsvSource({"1,1,2", "2,3,5", "10,-5,5"})
void addNumbers(int a, int b, int expected) {
    assertEquals(expected, calculator.add(a, b));
}

@ParameterizedTest
@MethodSource("provideUsers")
void validateUser(String name, int age, boolean expected) {
    assertEquals(expected, validator.isValid(name, age));
}

static Stream<Arguments> provideUsers() {
    return Stream.of(
        Arguments.of("Alice", 25, true),
        Arguments.of("", 25, false),
        Arguments.of("Bob", -1, false)
    );
}

@ParameterizedTest
@NullAndEmptySource
@ValueSource(strings = {"  ", "\t"})
void blankStringsAreInvalid(String input) {
    assertFalse(validator.isValid(input));
}
```

### Mocking with Mockito

```java
@ExtendWith(MockitoExtension.class)
class UserServiceTest {
    @Mock private UserRepository userRepo;
    @Mock private EmailService emailService;
    @InjectMocks private UserService userService;

    @Test
    void createUser_savesAndSendsEmail() {
        User user = new User("[email protected]", "Alice");
        when(userRepo.save(any(User.class))).thenReturn(user);

        User result = userService.createUser("[email protected]", "Alice");

        assertNotNull(result);
        verify(userRepo).save(any(User.class));
        verify(emailService).sendWelcomeEmail("[email protected]");
    }

    @Test
    void getUser_notFound_throwsException() {
        when(userRepo.findById(99L)).thenReturn(Optional.empty());
        assertThrows(UserNotFoundException.class, () -> userService.getUser(99L));
    }
}
```

### Nested Tests

```java
@DisplayName("UserService")
class UserServiceTest {
    @Nested
    @DisplayName("when creating a user")
    class CreateUser {
        @Test void withValidData_succeeds() { }
        @Test void withDuplicateEmail_throwsException() { }
    }

    @Nested
    @DisplayName("when deleting a user")
    class DeleteUser {
        @Test void existingUser_removesFromDb() { }
        @Test void nonExistentUser_throwsException() { }
    }
}
```

### Anti-Patterns

| Bad | Good | Why |
|-----|------|-----|
| `@Test public void test1()` | `@Test void shouldCalculateSum()` | Descriptive names |
| Testing private methods | Test via public API | Implementation detail |
| No @DisplayName | Always add display names | Better reporting |
| `assertEquals(true, x)` | `assertTrue(x)` | More readable |

## Maven Dependencies

```xml
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter</artifactId>
    <version>5.11.0</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-junit-jupiter</artifactId>
    <version>5.14.0</version>
    <scope>test</scope>
</dependency>
```

## Quick Reference

| Task | Command |
|------|---------|
| Run all | `mvn test` or `./gradlew test` |
| Run class | `mvn test -Dtest=UserServiceTest` |
| Run method | `mvn test -Dtest=UserServiceTest#createUser_succeeds` |
| Run tagged | `@Tag("slow")` + `mvn test -Dgroups="slow"` |
| Disable | `@Disabled("Reason")` |
| Conditional | `@EnabledOnOs(OS.LINUX)` |
| Timeout | `@Timeout(value = 5, unit = TimeUnit.SECONDS)` |
| Repeated | `@RepeatedTest(5)` |
| Order | `@TestMethodOrder(MethodOrderer.OrderAnnotation.class)` |

## Deep Patterns

For production-grade patterns, see `reference/playbook.md`:

| Section | What's Inside |
|---------|--------------|
| §1 Project Setup | Maven deps, parallel config, surefire |
| §2 Test Lifecycle | BeforeAll/Each, ordering, tags |
| §3 Parameterized | CsvSource, MethodSource, EnumSource, ValueSource |
| §4 Mockito | @Mock/@InjectMocks, captor, verify order |
| §5 Nested & Dynamic | @Nested grouping, @TestFactory |
| §6 AssertJ | Fluent assertions, extracting, collection checks |
| §7 Conditional | @EnabledOnOs, assumptions, @EnabledIf |
| §8 Custom Extensions | Timing, retry, BeforeTestExecution |
| §9 CI/CD | GitHub Actions with test reporter |
| §10 Debugging Table | 8 common problems with fixes |
| §11 Best Practices | 12-item production checklist |

© TestMu AI · MIT · LambdaTest/agent-skills

Similar skills

All skills for Testing and QA →

From the same set47

The whole set →
pytest-skill An agent skill that writes pytest tests for Python: fixtures, parametrize, markers, mocking and conftest patterns. Useful when you need test coverage without writing boilerplate by hand. CX Codex +1 442installs selenium-skill Generates production-grade Selenium WebDriver tests across six programming languages. Useful for local test suites or cloud execution on TestMu AI. CX Codex +1 333installs jest-skill Produces Jest unit and integration tests across JavaScript and TypeScript, covering mocks, snapshots, and React components. CX Codex +1 292installs cicd-pipeline-skill cicd-pipeline-skill generates CI/CD configs for test automation: GitHub Actions, Jenkins, GitLab CI, Azure DevOps. Includes TestMu AI cloud integration. CX Codex +1 290installs phpunit-skill This skill generates PHPUnit tests for PHP code, including assertions, data providers, mocks, and test doubles. Use it when you need tests shaped around a class or service. CX Codex +1 287installs cucumber-skill Creates Gherkin feature files and matching step definitions. Use it to turn application behavior into Cucumber BDD scenarios. CX Codex +1 283installs webdriverio-skill Generates WebdriverIO end-to-end tests in JavaScript or TypeScript for local runs and TestMu AI cloud. CX Codex +1 265installs cypress-skill Generates production-grade E2E and component tests in JavaScript or TypeScript. Runs tests locally or on TestMu AI cloud, understands Cypress commands, and writes tests with proper selectors and network interception. CX Codex +1 264installs

Project sponsors

Companies that keep this analytics open