Skip to content
Development
Command

/devkit.java.write-unit-tests

Generates comprehensive JUnit 5 unit tests for Java classes with Mockito mocking and AssertJ assertions. Use when writing unit tests for service, controller, or utility classes.

From plugin
developer-kit
37135 skills44 agents35 commands2 MCP
> /plugin marketplace add giuseppe-trisciuoglio/developer-kit
> /plugin install developer-kit@developer-kit

Command definition

devkit.java.write-unit-tests.md
allowed-tools: Read, Edit, Write, Bash, Grep, Glob
argument-hint: <class-file-path>
description: Generates comprehensive JUnit 5 unit tests for Java classes with Mockito mocking and AssertJ assertions. Use when writing unit tests for service, controller, or utility classes.
model: inherit

Generate Java Unit Tests

Overview

You are a Java testing expert specializing in JUnit 5, Mockito, and AssertJ. Generate comprehensive, maintainable unit tests following Spring Boot best practices.

Generates comprehensive JUnit 5 unit tests for Java classes with Mockito mocking and AssertJ assertions. Use when writing unit tests for service, controller, or utility classes.

Usage

/devkit.java.write-unit-tests $ARGUMENTS

Arguments

| Argument | Description | |--------------|------------------------------------------| | `$ARGUMENTS` | Combined arguments passed to the command |

Execution Instructions

**Agent Selection**: To execute this task, use the following agent with fallback:

  • Primary: `developer-kit-java:spring-boot-unit-testing-expert`
  • If not available: Use `developer-kit-java:spring-boot-unit-testing-expert` or fallback to `general-purpose` agent with

`spring-boot-test-patterns` skill

Instructions

1. Analyze the Java Class

Read and analyze the Java class provided in the argument: `$1`

Identify:

  • **Class type**: @Service, @RestController, @Component, utility class, mapper, validator, etc.
  • **Dependencies**: Injected repositories, clients, services, utilities
  • **Methods**: Public methods to test (ignore private methods)
  • **Business logic**: Workflows, validations, transformations, error handling
  • **Edge cases**: Null values, empty collections, boundary conditions, exceptions

2. Select Appropriate Testing Strategy

Based on the class type, apply the relevant skill:

**For @Service classes**:

  • Use skill: `unit-test-service-layer`
  • Mock all dependencies with @Mock
  • Use @InjectMocks for the service under test
  • Focus on business logic validation
  • Verify interactions with mocks

**For @RestController classes**:

  • Use skill: `unit-test-controller-layer`
  • Mock service dependencies
  • Test request/response handling
  • Verify HTTP status codes and response bodies
  • Test validation and error handling

**For mappers/converters**:

  • Use skill: `unit-test-mapper-converter`
  • Test bidirectional mappings
  • Test null handling
  • Test partial data scenarios

**For utility classes**:

  • Use skill: `unit-test-utility-methods`
  • Test static methods
  • Focus on edge cases and boundary conditions
  • No mocking needed

**For validation logic**:

  • Use skill: `unit-test-bean-validation`
  • Test Jakarta Bean Validation constraints
  • Test custom validators

**For exception handlers**:

  • Use skill: `unit-test-exception-handler`
  • Test all exception scenarios
  • Verify error response structure

**For caching logic**:

  • Use skill: `unit-test-caching`
  • Test cache hits and misses
  • Verify cache eviction

**For scheduled/async tasks**:

  • Use skill: `unit-test-scheduled-async`
  • Test scheduling logic
  • Test async execution

**For security/authorization**:

  • Use skill: `unit-test-security-authorization`
  • Test access control
  • Test authentication flows

**For external API clients**:

  • Use skill: `unit-test-wiremock-rest-api`
  • Mock HTTP responses with WireMock
  • Test retry logic and error handling

3. Generate Test Class Structure

Create a test class following these conventions:

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import static org.mockito.Mockito.*;
import static org.assertj.core.api.Assertions.*;

@ExtendWith(MockitoExtension.class) class [ClassName]

Test {

    @Mock
    private [Dependency]dependency;

    @InjectMocks
    private [ClassName]classUnderTest;

    // Test methods here
}

4. Generate Test Methods

For each public method, create tests covering:

**Happy path**:


@Test
void shouldReturnExpectedResult_whenValidInput() {
    // Arrange
    when(dependency.method()).thenReturn(expectedValue);

    // Act
    var result = classUnderTest.methodUnderTest(input);

    // Assert
    assertThat(result).isNotNull();
    assertThat(result.getField()).isEqualTo(expectedValue);
    verify(dependency).method();
}

**Edge cases** (use skill: `unit-test-boundary-conditions`):


@Test
void shouldHandleNullInput() {
    assertThatThrownBy(() -> classUnderTest.method(null))
            .isInstanceOf(IllegalArgumentException.class)
            .hasMessageContaining("must not be null");
}

@Test
void shouldHandleEmptyCollection() {
    var result = classUnderTest.method(List.of());
    assertThat(result).isEmpty();
}

**Exception scenarios**:


@Test
void shouldThrowException_whenDependencyFails() {
    when(dependency.method()).thenThrow(new RuntimeException("Error"));

    assertThatThrownBy(() -> classUnderTest.methodUnderTest())
            .isInstanceOf(ServiceException.class)
            .hasRootCauseInstanceOf(RuntimeException.class);
}

**Parameterized tests** (use skill: `unit-test-parameterized`):


@ParameterizedTest
@ValueSource(strings = {"valid1", "valid2", "valid3"})
void shouldAcceptValidInput(String input) {
    var result = classUnderTest.validate(input);
    assertThat(result).isTrue();
}

5. Follow Best Practices

  • **Naming**: Use descriptive test method names (should...When... pattern)
  • **AAA Pattern**: Arrange, Act, Assert clearly separated
  • **One assertion concept per test**: Test one behavior per method
  • **Fast tests**: No database, no network, no file I/O (< 50ms per test)
  • **Immutability**: Use final fields, records for test data
  • **AssertJ fluency**: Use fluent assertions for readability
  • **Verify interactions**: Use verify() to check mock interactions
  • **No magic values*
Read more
@giuseppe-trisciuoglio
Ships withdeveloper-kit

Modular plugin marketplace for Claude Code and agentic CLIs, with validated, spec-driven skills, agents, commands, and workflows for Java, TypeScript, Python, PHP, AWS, and AI.

371116 skills44 agents2 MCP
Get the whole plugin

Stars on GitHub

Momentum

stars in total
371
Star history of giuseppe-trisciuoglio/developer-kit on GitHub, a chart by star-history.com

Other commands on developer-kit.

More commands from other plugins.

build
Auto-invoked

build

Command

Implement tasks incrementally — build, test, verify, commit. Add "auto" to run the whole plan in one approved pass.

@addyosmani@addyosmaniInstall Command