JUnit & Mockito Unit Test Pattern

VerifiedSafe

Java unit test pattern using JUnit Jupiter and Mockito: mock field ordering, given/when/then phases, matchers in when() and real values in verify().

Sby Skills Guide Bot
TestingBeginner
8/13/2026
Claude Code
#junit5#mockito#java#unit-testing#test-conventions

Recommended for

Automated summary

Defines the mandated shape for JUnit Jupiter/Mockito unit tests in this repository: mock field ordering, named given/when/then phases, and verification with real values.

Strengths

  • Provides a full, copyable reference test (ControllerTest.java) instead of abstract rules
  • Specifies a three-group field layout and explains what each group represents
  • Covers the case where @InjectMocks cannot work and shows the @BeforeEach construction alternative
  • Scopes itself explicitly to *Test.java and excludes *IT.java failsafe/Testcontainers tests

Limitations

  • Tightly coupled to the registryatlas codebase and its specific classes (Controller, Service, CompanyProfile), so it is not portable as-is
  • The text cuts off mid-sentence in the section on folding given into when, leaving that rule incomplete
  • Says nothing about assertion styles beyond assertEquals or about parameterized tests
When to use it

Load it before writing or editing any *Test.java file in this repo so the house Mockito/JUnit structure is followed.

When not to use it

For *IT.java integration tests under failsafe/Testcontainers, or on a Java project that does not follow this convention.

Security analysis

Safe
Quality score80/100

Pure editorial style guide for writing JUnit Jupiter/Mockito tests. It contains no commands, no network or shell instructions, no file-system operations, no credential handling, and no attempt to disable agent safety behavior — only prose conventions and Java code samples. The one literal string ("api-key") is an obvious placeholder in an illustrative snippet, not a real secret.

No concerns found

How this analysis is made

Examples

New controller test
Write a ControllerTest for the new getCompanyById endpoint, following the repo's unit test pattern.
Refactor existing test layout
This test file has a blank line between every @Mock field — reorder the fields and regroup them per the unit-test-pattern skill.
Constructor with a plain String
Service now takes an API key string in its constructor; rewrite ServiceTest so it still follows the unit test pattern.

name: unit-test-pattern description: Sam's shape for JUnit Jupiter and Mockito unit tests — mock field ordering, given/when/then phases, matchers in when() and real values in verify(). Load before writing or editing any *Test.java in this repo.

Unit test pattern

Every unit test in this repo copies the shape of ControllerTest.java. JUnit Jupiter for assertions, Mockito for collaborators, three named phases, one mock field block in a fixed order.

This skill governs *Test.java only. *IT.java runs under failsafe against Testcontainers and is a different animal — nothing here applies to it.

The reference test

src/test/java/io/github/samrjthompson/registryatlas/companies/api/ControllerTest.java:

@ExtendWith(MockitoExtension.class)
public class ControllerTest {

    @Mock
    private Service service;

    @InjectMocks
    private Controller controller;

    @Test
    void shouldRetrieveCompaniesWithinFiveMileRadiusOfPostcode() {
        // given
        final String postcode = "G12 8AU";
        final long radius = 5L;

        when(service.getCompanies(anyString(), anyLong())).thenReturn(List.of());

        // when
        final ResponseEntity<List<String>> actual = controller.getCompanies(postcode, radius);

        // then
        assertEquals(HttpStatusCode.valueOf(HttpStatus.OK.value()), actual.getStatusCode());
        assertEquals(List.of(), actual.getBody());

        verify(service).getCompanies(postcode, radius);
    }
}

Field ordering

Three groups in this order, separated by a single blank line. Never put a blank line inside a group.

@Mock
private Service service;
@Mock
private Repository repository;

@InjectMocks
private Controller controller;

@Mock
private CompanyProfile companyProfile;
  1. Constructor dependencies of the class under test.
  2. The class under test.
  3. General mocks — every mock that is not a constructor dependency: a mocked argument passed to the method under test, or a mocked object a stub hands back.

Not this — a blank line between every @Mock loses the grouping the layout exists to show:

@Mock
private Service service;

@Mock
private Repository repository;

@InjectMocks
private Controller controller;

@Mock
private CompanyProfile companyProfile;

Constants go above all three groups, as in any Java class.

The grouping is for the reader. @InjectMocks injects by type and ignores field position, so a general mock whose type happens to match a constructor parameter is still injected — position does not prevent it.

When @InjectMocks will not do

If the constructor takes a String or another plain value Mockito cannot supply, drop @InjectMocks. Declare the field bare in the same middle position and build it in @BeforeEach void setUp(). The real dependencies keep their @Mock:

@ExtendWith(MockitoExtension.class)
public class ServiceTest {

    private static final String API_KEY = "api-key";

    @Mock
    private Client client;
    @Mock
    private Repository repository;

    private Service service;

    @Mock
    private CompanyProfile companyProfile;

    @BeforeEach
    void setUp() {
        service = new Service(client, repository, API_KEY);
    }
}

The three phases

Every test body is // given, // when, // then, each marker preceded by a blank line. This is the normal case, and most tests look exactly like it.

These markers are the sole exception to the no-code-comments skill. They mark structure rather than explain code, so they cannot rot. Nothing else in a test file may carry a comment — if a step needs explaining, rename the variable or the test method until it does not.

Folding two phases together

Where a phase would stand completely empty, fold it into its neighbour and combine the two markers.

Fold given into when only when there is nothing whatever to arrange — the method under test takes no arguments, or takes only mocks already declared at class level. Declaring a local is arranging, so a test carrying even one final String postcode = "G12 8AU"; keeps its own // given:

@Test
void shouldPassSuppliedCompanyToService() {
    // given / when
    controller.save(companyProfile);

    // then
    verify(service).save(companyProfile);
}

Fold when into then when the call under test happens inside the assertion, leaving no separate invocation to mark:

@Test
void shouldPropagateExceptionWhenPostcodeIsUnknown() {
    // given
    final String postcode = "ZZ99 9ZZ";
    final long radius = 5L;

    when(service.getCompanies(anyString(), anyLong())).thenThrow(new PostcodeNotFoundException());

    // when / then
    assertThrows(PostcodeNotFoundException.class, () -> controller.getCompanies(postcode, radius));
}

assertDoesNotThrow(() -> controller.getCompanies()) folds the same way.

Three separate markers stay the default. Reach for a combined marker because the test came out that shape, not to tighten a test that already reads fine.

Stubbing and verification

Real values never appear inside when(). They appear in the verify(…) arguments in the then step, which is what pins the contract:

// given
final String postcode = "G12 8AU";
final long radius = 5L;

when(service.getCompanies(anyString(), anyLong())).thenReturn(List.of());

// then
verify(service).getCompanies(postcode, radius);

Never when(service.getCompanies("G12 8AU", 5L)).

Reach for the type-specific matcher first — anyString(), anyLong(), anyInt(), anyList(). Use any(Foo.class) or eq(Foo.class) only where the extra specificity is genuinely required, such as picking between overloads or matching a class-literal argument:

when(restClient.get(anyString(), eq(CompanyProfile.class))).thenReturn(companyProfile);

Mockito is all-or-nothing about matchers: once one argument is a matcher, every argument must be. That is the only reason eq() exists — not as a way to smuggle a real value into a stub.

Assertions

JUnit Jupiter only, statically imported from org.junit.jupiter.api.Assertions — assertEquals, assertThrows, assertTrue, and the rest. AssertJ and Hamcrest are not on the classpath and adding either needs Sam's agreement first.

Static imports throughout: assertEquals, not Assertions.assertEquals; when and verify, not Mockito.when and Mockito.verify.

Naming and modifiers

  • Class is public, named <ClassUnderTest>Test, annotated @ExtendWith(MockitoExtension.class).
  • Test methods are package-private and void. No public.
  • Method names start should and carry both the behaviour and the condition: shouldRetrieveCompaniesWithinFiveMileRadiusOfPostcode, not testGetCompanies.
  • Locals are final.
  • The result of the call under test is named actual.

From the file to a first result

The download contains exactly the content displayed on this page. This copy may differ from the latest version in the source repository.

View the source and supporting files

This download contains SKILL.md only. Any scripts, references, templates and dependencies are not included. Get the required files from the source, preserving their directory structure, before continuing.

1. Download the file

Download SKILL.md

From the root of a test project, save the file as .skill-downloads/junit-mockito-unit-test-pattern-msr1u7k2/SKILL.md, or use the command below. This folder is for inspecting the skill before installation.

Command for macOS/Linux or WSL: requires a POSIX shell and curl. On Windows without WSL, use the download button and create the folder manually.

mkdir -p '.skill-downloads/junit-mockito-unit-test-pattern-msr1u7k2' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/junit-mockito-unit-test-pattern-msr1u7k2/download' --output '.skill-downloads/junit-mockito-unit-test-pattern-msr1u7k2/SKILL.md.part' && mv '.skill-downloads/junit-mockito-unit-test-pattern-msr1u7k2/SKILL.md.part' '.skill-downloads/junit-mockito-unit-test-pattern-msr1u7k2/SKILL.md'

2. Check prerequisites

Read SKILL.md before using it. If it references scripts or external services, inspect them and prepare the required access in your test environment.

No recognized prerequisites section in this file. This does not mean it is self-contained: libraries, tools and access requirements may be mentioned elsewhere in the content or source repository.

The platforms on this page are catalog indications. The paths below follow tool documentation; they do not prove this skill has been run in those tools. No minimum tool version is confirmed for this listing.

3. Load the skill

After inspection, copy the complete folder into your project using one of the commands below, then open a new tool session. The command stops if a folder with the same name already exists: compare the files before replacing it.

Claude Code
test -f '.skill-downloads/junit-mockito-unit-test-pattern-msr1u7k2/SKILL.md' && test -s '.skill-downloads/junit-mockito-unit-test-pattern-msr1u7k2/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/unit-test-pattern' && cp -R '.skill-downloads/junit-mockito-unit-test-pattern-msr1u7k2' '.claude/skills/unit-test-pattern'

OpenSkills

OpenSkills must already be installed. The local install/read procedure is checked with OpenSkills 1.5.0, which requires Node.js ≥ 20.6.0. Catalog slugs are not resolved automatically.

Official OpenSkills installation
openskills install './.skill-downloads/junit-mockito-unit-test-pattern-msr1u7k2'

openskills read 'junit-mockito-unit-test-pattern-msr1u7k2'

Reading should display the installed file content and its base directory. It does not run the skill or install its dependencies.

For an agent that reads AGENTS.md, then sync the index. This command changes AGENTS.md: review the diff before using it.

openskills sync

Manual method or another tool: attach SKILL.md to a conversation, or open it in an agent that can read files. Include any required supporting resources. No universal folder is recognized by every tool.

4. Try a first task

Use a short, synthetic input: an API endpoint, a small document or an interface brief. In a new conversation, attach the file or give the agent its path, then adapt this request:

Read .skill-downloads/junit-mockito-unit-test-pattern-msr1u7k2/SKILL.md and apply its instructions to this example: [describe a test input]. Identify any missing files, dependencies or access. Produce the result requested by the skill without inventing data or running unreviewed scripts.

Expected result: output matching the skill instructions, or a precise list of missing prerequisites. A read confirmation alone does not validate a first use. If an external resource is unavailable, that path remains untested.

Related skills