Security review

No findings observed

No concerns were reported in the reviewed catalog files. This is not a safety guarantee.

3 of 3 catalog files reviewed · (UTC)

Review details

AI instruction review via GitHub Agentic Workflows. Reviews inspect a recorded catalog snapshot; they do not execute skill files. AI can miss risks or report false positives.

Coverage is limited to catalog files. External links and upstream files absent from the catalog were not inspected.

Model
copilot/gpt-5.1-codex-mini
Rubric
1.0.0
Catalog commit
604d8c7ab66e2117b860e7b025dedb7d8bb0caf0
Content hash
36e39ad958d1633f67040f6082f098697acb268fd3d4571d10c372ea38278100
Reviewed files (3)
  • SKILL.md
  • references/assertj-and-mockito.md
  • references/build-setup.md
View full report (JSON)

Usage example

A discount calculator has boundary bugs around the minimum order amount.

Try a prompt like this

Add JUnit Jupiter parameterized tests for this discount calculator at amounts just below, exactly at, and above the eligibility threshold. Use the existing AssertJ and Mockito setup where appropriate, keep time deterministic, and do not skip existing failing tests.

Illustrative request, not an executed example or a guarantee of activation or results. Adapt it to your task after reviewing the skill’s instructions, prerequisites, and security review. Tool access and permissions depend on your setup.

Installation

Install as Agent Plugin Recommended
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install java-junit@skills-hub

Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled). Plugin java-junit v1.0.0 follows the Agent Plugins spec.

Install with the gh extension
gh skills-hub install java-junit

Don't have the extension? Run gh extension install samueltauil/skills-hub first.

Download and extract to your repository:

.github/skills/java-junit/

Extract the ZIP to .github/skills/ in your repo. The folder name must match java-junit for Copilot to auto-discover it.

Skill Files (3)

SKILL.md 8.2 KB
---
name: java-junit
description: 'Write, review and fix Java unit tests with JUnit 5 and JUnit 6 (Jupiter), AssertJ and Mockito: assertions, parameterized and nested tests, mocking rules, deterministic time and randomness, Surefire vs Failsafe, JaCoCo coverage, optional PIT mutation testing, and guardrails for agents (never skip or delete failing tests). Use when adding, refactoring or debugging tests in Maven or Gradle projects. Framework-neutral.'
---

# Java Testing with JUnit 5/6, AssertJ and Mockito

Framework-neutral guidance for fast, deterministic unit tests. For Spring slices use `spring-boot-testing` (if installed); for real databases/brokers in Docker use `java-testcontainers`; for failures you cannot explain, `java-debugging`.

## First: detect, don't impose

1. Read `pom.xml`/`build.gradle*`: JUnit version (`junit-jupiter`, `junit-bom`, or inherited from a Spring Boot BOM), assertion library, Mockito, Surefire/Failsafe versions, Java release.
2. Copy the conventions already in `src/test/java` (naming, assertion library, static imports, mocking style). Do not introduce AssertJ, Mockito or JaCoCo into a project that lacks them without asking.
3. Never bump the JUnit major version implicitly; upgrading is its own task (see `java-upgrade` if installed).

## JUnit 5 vs JUnit 6

| | JUnit 5 (last 5.14.x) | JUnit 6 (6.0 released; 6.1.x current) |
| --- | --- | --- |
| Java baseline | 8 | **17** (verified in the published Gradle module metadata) |
| Versioning | Platform 1.x, Jupiter 5.x, Vintage 5.x | One version number for Platform, Jupiter and Vintage |
| API | `org.junit.jupiter.api.*` | Same packages; the Jupiter tests in this skill compile and pass unchanged on 5.14.4 and 6.0.3 |
| Removed in 6.0 | | `MethodOrderer.Alphanumeric`, the deprecated two-argument `InvocationInterceptor.interceptDynamicTest(Invocation, ExtensionContext)` overload (the three-argument one remains), `junit.jupiter.tempdir.scope`, `@CsvFileSource(lineSeparator)` |
| CSV | univocity-parsers | FastCSV: stricter parsing (no characters after a closing quote); header-field options now apply to headers |
| Other | | `junit-jupiter-migrationsupport` deprecated; invalid enum-style config values now fail discovery; `@Nested` class order deterministic but non-obvious |

Source: JUnit 6.0.0 release notes (<https://docs.junit.org/6.0.0/release-notes.html>). Read the notes for the target version (<https://docs.junit.org/current/release-notes/>) and prefer them over this table. JUnit 4 tests need the Vintage engine; do not mix `org.junit.Test` and `org.junit.jupiter.api.Test` in one class.

Dependencies (same for 5 and 6; verified with Maven and Gradle): import `org.junit:junit-bom`, then declare `org.junit.jupiter:junit-jupiter` (aggregates api, params, engine) with `test` scope. Gradle 9 additionally **requires** `testRuntimeOnly("org.junit.platform:junit-platform-launcher")` (verified: without it the test executor fails with "Failed to load JUnit Platform") and `tasks.test { useJUnitPlatform() }`. Maven needs Surefire 3.x (verified with 3.6.0).

## Assertions

Match the project's library. Plain Jupiter rules: expected value first, lazy `Supplier` messages, `assertAll`, `assertThrowsExactly`, timeouts. (The separate `instructions/java-junit5-assertions.instructions.md` resource has the longer version but is not installed with this skill.) If the project uses AssertJ, prefer it for collections, strings and exceptions; patterns (soft assertions, `assertThatThrownBy`, `extracting`, `containsExactly`, `usingRecursiveComparison`) are in `references/assertj-and-mockito.md`.

- Assert on outcomes and state, not on how many times internals were called.
- Compare values; avoid bare `assertNotNull`.
- Never catch `AssertionError`/`Exception` to make a test pass.

## Mocking (Mockito)

- Mock **collaborators across a boundary** (repository, HTTP client, clock, message sender). Do **not** mock value objects, records, collections, `String`, or the class under test; use real instances or simple fakes.
- Prefer a hand-written fake over a mock when the interaction is stateful.
- Use `@ExtendWith(MockitoExtension.class)` with `@Mock`/`@InjectMocks`/`@Captor`. Strict stubs are the default there, so an unused stub fails the test (`UnnecessaryStubbingException`). Fix the test; relax with `@MockitoSettings(strictness = Strictness.LENIENT)` only for a justified shared setup.
- Mockito 5 uses the inline mock maker by default. On JDK 21+ it may self-attach and print a dynamic-agent warning. With **Mockito 5.14.0+**, register `mockito-core` as a `-javaagent` instead (setup for Maven and Gradle in `references/assertj-and-mockito.md`, verified on JDK 21 and 25). Check the resolved version first: earlier 5.x jars lack `Premain-Class` and cannot be used as the agent. Ask before upgrading; otherwise use the instrumentation setup documented for the installed version.
- Mockito 5 requires Java 11+. Its default inline mock maker does not work on GraalVM native image, where the subclass mock maker is appropriate (Mockito 5.0.0 release notes, <https://github.com/mockito/mockito/releases/tag/v5.0.0>).
- Avoid `mockStatic`/`mockConstruction`; wrap the static call behind an interface.

## Determinism

- Time: inject `java.time.Clock` (`Clock.fixed(...)`) and call `Instant.now(clock)`; avoid `Instant.now()`/`LocalDate.now()` in code under test.
- Randomness: inject a `Random`/`RandomGenerator` with a fixed seed; log the seed if generated.
- Do not depend on default locale, time zone, file encoding, network, or wall-clock sleeps. Set them explicitly (newer 6.x releases add built-in locale/time-zone/system-property extensions; check the release notes of your version, otherwise use try/finally).

## Unit vs integration tests

| | Unit (`*Test`) | Integration (`*IT`) |
| --- | --- | --- |
| Maven | Surefire, `mvn test` | Failsafe, `mvn verify` |
| Gradle | `test` task | separate `integrationTest` task (JVM Test Suite) wired into `check` |
| Speed | milliseconds, no I/O | may use Docker/DB |

Surefire defaults pick `*Test`, `Test*`, `*Tests`, `*TestCase`; Failsafe picks `*IT`, `IT*`, `*ITCase`. Failsafe needs the `integration-test` and `verify` goals bound and is run by `mvn verify`, not `mvn test`. Alternatively split by `@Tag`. For databases and brokers see `java-testcontainers`; for Spring slices see `spring-boot-testing`. Full build snippets: `references/build-setup.md`.

## Coverage and mutation testing (optional)

- JaCoCo: add only if the project uses it or the user asks. With Surefire/Failsafe use `<argLine>@{argLine} ...</argLine>` so the JaCoCo agent is not overwritten.
- Coverage is a smell detector, not a goal; never add assertion-free tests to raise a number, and do not add a coverage gate the project lacks.
- PIT (mutation testing) is slow; run it on changed classes only if the project already uses it or the user asks (see `references/build-setup.md`, which records a verified pitest-maven + JUnit 5 plugin run).

## Agent guardrails

1. **Never** delete, comment out, `@Disabled`, weaken (looser assertion, wider tolerance, swallowed exception) or skip a failing test to get green. Find the cause.
2. Decide which side is wrong, the test or the production code. If the fix changes **production behavior**, stop and ask the user first; if the test encodes an obviously stale expectation, say so and propose the change.
3. Do not add `-DskipTests`, `-Dmaven.test.skip`, `-x test` or `failIfNoTests=false` to make a build pass.
4. Do not mock the class under test or assert on mock internals to "prove" correctness.
5. Run the narrowest test first, then the full build:
   - Maven: `mvn -q -Dtest=OrdersTest test` (one method: `-Dtest='OrdersTest#place_should_saveAndNotify_when_itemValid'`), then `mvn verify`.
   - Gradle: `./gradlew test --tests 'demo.OrdersTest'`, then `./gradlew check`.
   Prefer the project wrapper (`./mvnw`, `./gradlew`) when present.
6. Flaky test: reproduce by rerunning, then remove the nondeterminism (time, order, shared state, async waits); do not add retries.
7. New code gets new tests beside the existing ones, in the same style: happy path, boundaries, error cases.

## References

- `references/assertj-and-mockito.md`: AssertJ patterns, Mockito strictness/captors/agent setup, when not to mock.
- `references/build-setup.md`: Maven and Gradle (Kotlin DSL) setups for JUnit 5/6, Failsafe split, JaCoCo, PIT.
references/
assertj-and-mockito.md 7.4 KB
# AssertJ and Mockito patterns

All snippets compile and pass on JDK 21 (AssertJ 3.27.7, Mockito 5.23.0, JUnit 5.14.4 and 6.0.3), except where marked.

## AssertJ

Use only if the project already depends on `org.assertj:assertj-core` (or the user agrees). Import statically from `org.assertj.core.api.Assertions`.

```java
// collections
assertThat(people).hasSize(2).extracting(Person::name).containsExactly("Ann", "Bob");
assertThat(people).extracting(Person::name, Person::age)
    .containsExactlyInAnyOrder(tuple("Bob", 25), tuple("Ann", 30));
assertThat(people).filteredOn(p -> p.age() > 26).singleElement();
assertThat(people).allSatisfy(p -> assertThat(p.age()).isPositive());
assertThat(Map.of("k", 1)).containsOnly(entry("k", 1));

// object graphs (records and POJOs without equals)
assertThat(actual).usingRecursiveComparison().isEqualTo(expected);

// exceptions
assertThatThrownBy(() -> Integer.parseInt("x"))
    .isInstanceOf(NumberFormatException.class)
    .hasMessageContaining("\"x\"");
assertThatExceptionOfType(IllegalStateException.class)
    .isThrownBy(() -> service.run())
    .withMessage("boom")
    .withCauseInstanceOf(RuntimeException.class);
assertThatCode(() -> parse("1")).doesNotThrowAnyException();

// optionals
assertThat(Optional.of("x")).contains("x");
assertThat(Optional.empty()).isEmpty();
```

Prefer `containsExactly` (order matters) or `containsExactlyInAnyOrder` over `contains`, which passes with extra elements. `extracting` gives readable diffs on failure.

### Soft assertions (report all failures)

```java
SoftAssertions.assertSoftly(s -> {
    s.assertThat(result.status()).isEqualTo(200);
    s.assertThat(result.body()).contains("ok");
});
```

or per class with the JUnit extension (bundled in `assertj-core`):

```java
@ExtendWith(SoftAssertionsExtension.class)
class ResultTest {
    @InjectSoftAssertions SoftAssertions softly;   // org.assertj.core.api.junit.jupiter
    @Test void t() { softly.assertThat(1).isEqualTo(1); }
}
```

Jupiter equivalent: `assertAll(() -> ..., () -> ...)`.

AssertJ 4 was only at milestone releases when this was written; stay on 3.x unless the project already uses 4.

## Mockito

Dependency: `org.mockito:mockito-junit-jupiter` (brings `mockito-core`).

```java
@ExtendWith(MockitoExtension.class)
class OrdersTest {
    @Mock Orders.Repo repo;
    @Mock Orders.Notifier notifier;
    @Captor ArgumentCaptor<String> message;

    @Test
    void place_should_saveAndNotify() {
        var orders = new Orders(repo, notifier, FIXED_CLOCK);   // construct explicitly; prefer over @InjectMocks
        var result = orders.place("book");

        verify(repo).save(result);
        verify(notifier).send(message.capture());
        assertThat(message.getValue()).startsWith("placed book");
    }

    @Test
    void require_should_throw_when_missing() {
        when(repo.find(7L)).thenReturn(Optional.empty());
        ...
    }
}
```

- **Strictness**: `MockitoExtension` uses strict stubs. Verified: a stub that is never used fails the test with `UnnecessaryStubbingException`. Argument mismatches on a stubbed method are also reported (`PotentialStubbingProblem`). Per class/nested class opt-out: `@MockitoSettings(strictness = Strictness.LENIENT)`; per stub: `lenient().when(...)`.
- **Stubbing**: `when(x.m()).thenReturn(v)`; for `void` or to throw: `doThrow(...).when(x).m()`. Prefer returning values over verifying calls.
- **Verification**: verify side effects that are the behavior (a message sent, an entity saved). Use `verify(x, never()).m()` for "must not happen". Avoid `verifyNoMoreInteractions` as a default; it couples tests to implementation.
- **Captors**: `@Captor ArgumentCaptor<T>` or `ArgumentCaptor.forClass(T.class)`; assert on `getValue()`/`getAllValues()`.
- **Argument matchers**: if one argument uses a matcher (`any()`, `eq()`), all must.
- **Do not mock**: records/value objects, collections, `String`, types you own that are simple data, the class under test, `java.time.Clock` (use `Clock.fixed`). Prefer an in-memory fake repository over a mock when the test would otherwise stub several calls.
- **Mock only what you own at the boundary**; wrap third-party types in your own interface and mock that.

### Inline mock maker and the JDK 21+ agent warning

Mockito 5 uses the inline mock maker by default. On JDK 21+ without an agent, Mockito self-attaches and the build prints:

```
Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. ...
WARNING: A Java agent has been loaded dynamically (.../byte-buddy-agent-....jar)
WARNING: Dynamic loading of agents will be disallowed by default in a future release
```

For **Mockito 5.14.0+ only**, fix by registering `mockito-core` as an agent (verified: warnings gone on JDK 21). The agent entry point was introduced in [Mockito 5.14.0](https://github.com/mockito/mockito/releases/tag/v5.14.0); earlier 5.x jars lack the `Premain-Class` manifest entry, so using them with `-javaagent` aborts the test JVM.

Before applying either snippet below, check the resolved `mockito-core` version (`./mvnw dependency:tree -Dincludes=org.mockito:mockito-core` or `./gradlew dependencyInsight --dependency mockito-core --configuration testRuntimeClasspath`). Preserve the project's BOM/version-catalog management and ask before upgrading. If the version is below 5.14.0 and no upgrade is approved, do not use these snippets; follow that version's documented instrumentation setup.

Maven (`maven-dependency-plugin` `properties` goal exposes `${org.mockito:mockito-core:jar}`; keep `@{argLine}` when JaCoCo is used):

```xml
<plugin>
  <artifactId>maven-dependency-plugin</artifactId>
  <executions>
    <execution><goals><goal>properties</goal></goals></execution>
  </executions>
</plugin>
<plugin>
  <artifactId>maven-surefire-plugin</artifactId>
  <configuration>
    <argLine>@{argLine} -javaagent:${org.mockito:mockito-core:jar}</argLine>
  </configuration>
</plugin>
```

(Without JaCoCo, drop `@{argLine}`; with a literal `@{argLine}` and no JaCoCo `prepare-agent`, Maven leaves it unresolved and the JVM fails to start.) Add the same `argLine` to Failsafe if integration tests use Mockito.

Gradle (Kotlin DSL):

```kotlin
val mockitoAgent: Configuration by configurations.creating
dependencies {
    testImplementation("org.mockito:mockito-junit-jupiter:5.23.0")
    mockitoAgent("org.mockito:mockito-core:5.23.0") { isTransitive = false }
}
tasks.test { jvmArgs("-javaagent:${mockitoAgent.asPath}") }
```

Keep the two Mockito versions identical (or use a BOM/version catalog). On JDK 25, ByteBuddy may still print a `sun.misc.Unsafe` "terminally deprecated" warning; it is harmless noise from the dependency (seen with byte-buddy 1.18.3). Do not "fix" it with `--add-opens` flags unless a test actually fails.

## Parameterized and nested tests

```java
@ParameterizedTest
@NullAndEmptySource
@ValueSource(strings = {" ", "\t"})
void rejectsBlank(String item) { ... }

@ParameterizedTest(name = "sign({0}) = {1}")
@CsvSource({"-5,-1", "0,0", "9,1"})
void sign(int in, int out) { ... }

@ParameterizedTest
@MethodSource("pairs")
void viaMethodSource(int in, int out) { ... }
static Stream<Arguments> pairs() { return Stream.of(Arguments.of(-2, -1), Arguments.of(2, 1)); }
```

`@Nested` classes see the outer class's mocks and `@BeforeEach`. Maven reports each nested class as its own test class (`OrdersTest$Evens`) and the outer class may show `Tests run: 0`; that is expected, check the total.
build-setup.md 4.8 KB
# Build setup for JUnit 5/6

Versions below were used in verification runs (JDK 21 and 25, Maven 3.10.0, Gradle 9.8.1). Re-check current releases on Maven Central before pinning, and keep the project's existing versions when present.

## Maven

```xml
<properties>
  <junit.version>6.0.3</junit.version>      <!-- 5.14.4 works with the same test code; Java baseline 17 for 6.x -->
</properties>
<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>org.junit</groupId>
      <artifactId>junit-bom</artifactId>
      <version>${junit.version}</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>
<dependencies>
  <dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter</artifactId>
    <scope>test</scope>
  </dependency>
</dependencies>
<build>
  <plugins>
    <plugin>
      <artifactId>maven-surefire-plugin</artifactId>
      <version>3.6.0</version>
    </plugin>
    <plugin>
      <artifactId>maven-failsafe-plugin</artifactId>
      <version>3.6.0</version>
      <executions>
        <execution>
          <goals><goal>integration-test</goal><goal>verify</goal></goals>
        </execution>
      </executions>
    </plugin>
  </plugins>
</build>
```

Switching versions for a trial run: `mvn verify -Djunit.version=5.14.4` (works because the version is a property). If a parent (e.g. Spring Boot) manages JUnit, override that property or BOM deliberately and tell the user.

Commands: `mvn test` (unit, Surefire), `mvn verify` (unit + `*IT` via Failsafe), `mvn -Dtest=FooTest#bar test`, `mvn -Dit.test=FooIT verify`.

### JaCoCo (0.8.15)

```xml
<plugin>
  <groupId>org.jacoco</groupId>
  <artifactId>jacoco-maven-plugin</artifactId>
  <version>0.8.15</version>
  <executions>
    <execution><goals><goal>prepare-agent</goal></goals></execution>
    <execution>
      <id>report</id><phase>verify</phase><goals><goal>report</goal></goals>
    </execution>
    <!-- optional gate; only if the project already enforces one -->
    <execution>
      <id>check</id><phase>verify</phase><goals><goal>check</goal></goals>
      <configuration>
        <rules><rule><element>BUNDLE</element>
          <limits><limit><counter>LINE</counter><value>COVEREDRATIO</value><minimum>0.80</minimum></limit></limits>
        </rule></rules>
      </configuration>
    </execution>
  </executions>
</plugin>
```

If Surefire/Failsafe set `<argLine>`, it must start with `@{argLine}`, otherwise the JaCoCo agent is dropped. Conversely, a literal `@{argLine}` without a `prepare-agent` execution fails the forked JVM (`Error: could not open '{argLine}'`, verified). Report: `target/site/jacoco/index.html`.

### PIT mutation testing (verified: pitest-maven 1.30.1 + pitest-junit5-plugin 1.2.3 with JUnit 6.0.3 on JDK 21)

```xml
<plugin>
  <groupId>org.pitest</groupId>
  <artifactId>pitest-maven</artifactId>
  <version>1.30.1</version>
  <dependencies>
    <dependency>
      <groupId>org.pitest</groupId>
      <artifactId>pitest-junit5-plugin</artifactId>
      <version>1.2.3</version>
    </dependency>
  </dependencies>
  <configuration>
    <targetClasses><param>com.example.*</param></targetClasses>
  </configuration>
</plugin>
```

Run: `mvn test-compile org.pitest:pitest-maven:mutationCoverage` (report in `target/pit-reports`). PIT reads Surefire's `argLine` too; if it contains an unresolved `@{argLine}`, pass `-DargLine=-Dpit=1` for the PIT run (verified workaround). Gradle equivalent: the `info.solidsoft.pitest` plugin (not verified here).

## Gradle (Kotlin DSL)

```kotlin
plugins { java; jacoco }
repositories { mavenCentral() }

dependencies {
    testImplementation(platform("org.junit:junit-bom:6.0.3"))
    testImplementation("org.junit.jupiter:junit-jupiter")
    testRuntimeOnly("org.junit.platform:junit-platform-launcher")   // required with Gradle 9
}

tasks.test {
    useJUnitPlatform()
    finalizedBy(tasks.jacocoTestReport)
}
```

Integration tests as a JVM Test Suite (verified; `src/integrationTest/java`):

```kotlin
testing {
    suites {
        register<JvmTestSuite>("integrationTest") {
            useJUnitJupiter("6.0.3") // a custom suite does not inherit the unit tests' BOM; keep the versions equal
            dependencies { implementation(project()) }
            targets.all { testTask.configure { shouldRunAfter(tasks.test) } }
        }
    }
}
tasks.check { dependsOn(testing.suites.named("integrationTest")) }
```

Commands: `./gradlew test`, `./gradlew test --tests 'demo.OrdersTest'` (also runs its nested classes), `./gradlew check`, report at `build/reports/tests/test/index.html` and `build/reports/jacoco`. Trial run on JUnit 5: `./gradlew test -PjunitVersion=5.14.4` when the version is read from a Gradle property.

Groovy DSL differs only in syntax (`testImplementation platform('org.junit:junit-bom:6.0.3')`, `jvmArgs '-javaagent:...'`).

License (MIT)

View full license text
MIT License

Copyright GitHub, Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.