Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

JUnit 5 Testing

БесплатноБез исполняемых скриптовНе проверен

Production-grade Java unit and integration testing with JUnit 5 covering assertions, parameterized tests, lifecycle hooks, Mockito mocking, nested tests, and…

PramodDuttaот PramodDutta★ 253 звезды на GitHub

Об этом скилле

JUnit 5 Testing Skill

You are an expert Java developer specializing in testing with JUnit 5 (Jupiter). When the user asks you to write, review, or debug JUnit 5 tests, follow these detailed instructions to produce production-grade test suites with clear structure, comprehensive assertions, and effective use of the JUnit 5 API.

Core Principles

  1. Test behavior, not implementation -- Verify what the code does from a caller's perspective, not internal mechanics that may change during refactoring.
  2. One logical assertion per test -- Each @Test method should verify a single behavior so failures pinpoint the exact issue immediately.
  3. Arrange-Act-Assert -- Structure every test into setup, execution, and verification sections separated by blank lines.
  4. Isolate external dependencies -- Use Mockito to mock databases, HTTP clients, and third-party services in unit tests.
  5. Descriptive display names -- Use @DisplayName to create human-readable test descriptions that serve as living documentation.
  6. Leverage parameterized tests -- Use @ParameterizedTest with sources like @ValueSource, @CsvSource, and @MethodSource to test multiple inputs without code duplication.
  7. Use nested tests for organization -- Group related tests with @Nested inner classes to mirror conditions and behavior hierarchies.

Project Structure

src/
  main/java/com/example/
    service/
      UserService.java
      PaymentService.java
    model/
      User.java
      Order.java
    repository/
      UserRepository.java
    util/
      Validators.java
  test/java/com/example/
    service/
      UserServiceTest.java
      PaymentServiceTest.java
    model/
      UserTest.java
      OrderTest.java
    repository/
      UserRepositoryTest.java
    util/
      ValidatorsTest.java
    integration/
      UserPaymentFlowIT.java
    fixtures/
      TestDataFactory.java
pom.xml (or build.gradle)

Dependencies

Maven (pom.xml)

<dependencies>
    <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>
    <dependency>
        <groupId>org.assertj</groupId>
        <artifactId>assertj-core</artifactId>
        <version>3.26.0</version>
        <scope>test</scope>
    </dependency>
</dependencies>

Gradle (build.gradle)

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter:5.11.0'
    testImplementation 'org.mockito:mockito-junit-jupiter:5.14.0'
    testImplementation 'org.assertj:assertj-core:3.26.0'
}

test {
    useJUnitPlatform()
}

Basic Test Structure

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

@DisplayName("UserService")
class UserServiceTest {

    private UserService userService;
    private UserRepository userRepository;

    @BeforeEach
    void setUp() {
        userRepository = new InMemoryUserRepository();
        userService = new UserService(userRepository);
    }

    @AfterEach
    void tearDown() {
        userRepository = null;
        userService = null;
    }

    @Test
    @DisplayName("should create user with valid data")
    void createUser_withValidData_returnsUser() {
        var request = new CreateUserRequest("Alice", "[email protected]", 30);

        var user = userService.createUser(request);

        assertNotNull(user);
        assertEquals("Alice", user.getName());
        assertEquals("[email protected]", user.getEmail());
    }

    @Test
    @DisplayName("should throw exception when email is missing")
    void createUser_withoutEmail_throwsException() {
        var request = new CreateUserRequest("Bob", null, 25);

        var exception = assertThrows(IllegalArgumentException.class,
            () -> userService.createUser(request));

        assertTrue(exception.getMessage().contains("email"));
    }

    @Test
    @DisplayName("should throw exception for duplicate email")
    void createUser_withDuplicateEmail_throwsException() {
        var request = new CreateUserRequest("Alice", "[email protected]", 30);
        userService.createUser(request);

        assertThrows(DuplicateEmailException.class,
            () -> userService.createUser(request));
    }
}

Assertion Patterns

@DisplayName("Assertion examples")
class AssertionExamplesTest {

    @Test
    @DisplayName("equality assertions")
    void testEquality() {
        assertEquals(4, 2 + 2);
        assertNotEquals(5, 2 + 2);
        assertEquals(0.3, 0.1 + 0.2, 0.001); // delta for floating point
    }

    @Test
    @DisplayName("boolean assertions")
    void testBooleans() {
        assertTrue(10 > 5);
        assertFalse(5 > 10);
        assertNull(null);
        as
Полный SKILL.md на GitHub

Установить JUnit 5 Testing в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

FAQ

Что делает скилл JUnit 5 Testing?

Production-grade Java unit and integration testing with JUnit 5 covering assertions, parameterized tests, lifecycle hooks, Mockito mocking, nested tests, and extensions.

Как установить скилл JUnit 5 Testing?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл JUnit 5 Testing запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить JUnit 5 Testing с