Skip to main content
command CX Codex

devkit.java.write-unit-tests — Claude Code command

devkit.java.write-unit-tests generates JUnit 5 tests with Mockito and AssertJ assertions from a Java class path. Useful for testing Spring Boot services, controllers, and utility classes.

MIT ★ 372 updated 2026-09-10

Install into Claude Code · Plugin marketplace All methods and platforms ↓
/plugin marketplace add giuseppe-trisciuoglio/developer-kit
/plugin install developer-kit-java@developer-kit
Open on GitHub

What devkit.java.write-unit-tests does

This command inspects the target Java file, detects the component architecture (@Service, @RestController, converter, or utility), and builds a test class. It relies on the Read, Edit, Write, Bash, Grep, and Glob tools. Generated suites skip loading the Spring application context, ensuring tests run quickly via mvn test.

Execution targets the developer-kit-java:spring-boot-unit-testing-expert subagent, falling back to a general-purpose agent when unavailable. It applies distinct strategies per component: Mockito @InjectMocks workflows for services, HTTP status validations for controllers, and boundary checks without mocks for static utilities.

The command expects a specific class file path as an argument. Providing an invalid path prevents the assistant from placing the generated test under src/test/java/.

What it helps with

  • generate JUnit 5 tests using Mockito and AssertJ
  • cover edge cases and exception handling for Spring services
  • build isolated controller tests without starting the Spring context

Example prompts for the agent

  • /devkit.java.write-unit-tests src/main/java/com/example/UserService.java
  • /devkit.java.write-unit-tests src/main/java/com/example/OrderController.java

How to install devkit.java.write-unit-tests

1Plugin marketplace

/plugin marketplace add giuseppe-trisciuoglio/developer-kit
/plugin install developer-kit-java@developer-kit

2Manually: put the files in place

.claude/commands/devkit.java.write-unit-tests.md

Call it with /devkit.java.write-unit-tests. For all projects use ~/.claude/commands/

Questions about devkit.java.write-unit-tests

How to install devkit.java.write-unit-tests in Claude Code?

Run /plugin marketplace add giuseppe-trisciuoglio/developer-kit followed by /plugin install developer-kit-java@developer-kit.

What does devkit.java.write-unit-tests do?

It examines public methods in a Java class and creates a test file using JUnit 5, Mockito mocking, and AssertJ assertions.

Does it start an entire Spring Boot context?

No, it focuses strictly on unit tests with MockitoExtension to keep execution fast without starting a Spring environment.

Source text

devkit.java.write-unit-tests.md · MIT
---
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:

```java
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**:

```java

@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`):

```java

@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**:

```java

@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`):

```java

@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**: Use constants or factory methods for test data

### 6. Generate Complete Test File

Create the complete test file at the correct location:

- If source is `src/main/java/com/example/UserService.java`
- Test goes to `src/test/java/com/example/UserServiceTest.java`

Include:

- All necessary imports
- MockitoExtension configuration
- Mock and InjectMocks declarations
- All test methods
- Helper methods if needed

### 7. Verify Test Quality

After generating tests:

- Ensure all public methods are covered
- Check edge cases are tested
- Verify no hardcoded values
- Confirm no Spring context is loaded
- Run tests with: `mvn test -Dtest=[ClassName]Test`

## Available JUnit Skills Reference

Leverage these skills for specific scenarios:

- `unit-test-application-events` - Testing Spring application events
- `unit-test-bean-validation` - Testing Jakarta Bean Validation
- `unit-test-boundary-conditions` - Edge cases and boundary testing
- `unit-test-caching` - Testing cache behaviors
- `unit-test-config-properties` - Testing @ConfigurationProperties
- `unit-test-controller-layer` - Testing REST controllers
- `unit-test-exception-handler` - Testing exception handlers
- `unit-test-json-serialization` - Testing JSON serialization
- `unit-test-mapper-converter` - Testing mappers and converters
- `unit-test-parameterized` - Parameterized testing patterns
- `unit-test-scheduled-async` - Testing scheduled/async tasks
- `unit-test-security-authorization` - Testing security
- `unit-test-service-layer` - Testing service layer with Mockito
- `unit-test-utility-methods` - Testing utility classes
- `unit-test-wiremock-rest-api` - Testing external APIs with WireMock

## Examples

```bash
/developer-kit-java:devkit.java.write-unit-tests src/main/java/com/example/service/UserService.java
```

This will analyze UserService.java, identify it as a @Service class, apply the service-layer testing strategy, and
generate a comprehensive UserServiceTest.java with all necessary test cases.

© Giuseppe Trisciuoglio · MIT · giuseppe-trisciuoglio/developer-kit

Similar slash commands

All slash commands for Testing and QA →

From the same set191

The whole set →
nestjs-testing nestjs-testing — a rule for NestJS projects: enforces TestingModule for mocked dependencies with Jest, structures E2E tests with Supertest, and prevents real API or database calls during testing. CX Codex +1 ★ 372repo stars nestjs-database-expert nestjs-database-expert — a subagent for Claude Code dedicated to database operations in NestJS, focusing on Drizzle ORM schemas, migrations, transactions, and query patterns. CX Codex ★ 372repo stars devkit.verify-skill devkit.verify-skill is a Claude Code command that checks a skill against DevKit requirements, its template, and dependencies. Run it before publishing or after edits. CX Codex +1 ★ 372repo stars aws-cloudformation-dynamodb aws-cloudformation-dynamodb — a Claude skill that supplies CloudFormation patterns for DynamoDB tables: keys, indexes, billing modes, TTL and streams. Handy when infrastructure lives in code. CX Codex +1 ★ 372repo stars clean-architecture Guides Clean Architecture, DDD, and Hexagonal Architecture in NestJS/TypeScript projects. Use it to shape domain models or separate business rules from framework code. CX Codex +1 ★ 372repo stars spring-boot-backend-development-expert spring-boot-backend-development-expert — a Claude subagent for Spring Boot work: implements REST endpoints, JPA layers and JWT security, and writes the matching tests. CX Codex ★ 372repo stars java-security-expert java-security-expert runs security audits for Java and Spring Boot applications, detects OWASP vulnerabilities, reviews OAuth2 flows, and checks compliance. CX Codex ★ 372repo stars general-code-reviewer The general-code-reviewer subagent checks code changes for bugs, security flaws, and quality problems, reporting only findings with a confidence score of at least 80. CX Codex ★ 372repo stars

Project sponsors

Companies that keep this analytics open