SteelReed

Search

Search posts, questions…

5. Spring Boot

Unit tests when AI writes them for you: test decisions, not wiring (JUnit and Mockito)

AI can generate dozens of green tests in seconds; the question is whether they go red when the logic is wrong. What to unit-test, AAA, JUnit 5/6, Mockito (stubs, mocks, spies, fakes, strict stubs, ArgumentCaptor), injecting a Clock, how to review AI-written tests, and measuring with mutation testing instead of coverage.

18 Nov 20268 min readMid

–

1. The problem

The AI generates 40 tests for DiscountService: 92% coverage, CI green. A PR changes >= to > at the 500,000 VND threshold, and no test fails. Customers spending exactly 500,000 VND lose their discount for two weeks. The tests only tried 100,000 and 1,000,000.

2. Key idea

A test can only catch a bug if at least one wrong implementation makes it fail. Tests that mirror the implementation, or never touch boundary values, pass for correct and broken code alike.

Weak test Why it stays green How to spot it
Mirror test stub findById, call, assert what was stubbed no branch or calculation is checked
Missing boundaries only values far from the threshold no 499,999 or 500,000
Over-broad stubs any() matches even the wrong id anyString(), any() everywhere
Verify instead of assert checks "was called", not the result verify(...) without assertThat
Mocked value objects the test checks the mock, not the logic mock(Money.class)

2.1 Which technique?

Technique Use when Don't use when
Unit test (no Spring) business branches, pricing, normalization, required ordering a method that just calls a repository and returns
Slice / integration test JSON mapping, queries, transactions, UNIQUE constraints pure logic already unit-tested
Mock (Mockito) dependencies you own: repositories, a Notifier value objects, DTOs, records, the class under test
verify / never() the side effect is the outcome: saving, sending mail queries: assert results instead
Mutation testing (PIT) packages with important logic, run nightly every commit across the whole repo

The test pyramid is a cost principle, not a mandatory ratio: for a CRUD service, integration tests make up most of it. Time always comes through an injected Clock, never Instant.now() in code under test.

3. In Java

AAA (Arrange, Act, Assert), one behavior per test, stubs with concrete values, and assertions on what must not happen too.

JAVA
@ExtendWith(MockitoExtension.class)                   // strict stubs: an unused stub fails the test
class UserServiceTest {
    @Mock UserRepository users;
    @Mock PasswordEncoder encoder;
    @InjectMocks UserService service;
 
    @Test
    void rejectsDuplicateEmailWithoutHashingOrSaving() {
        when(users.existsByEmailIgnoreCase("[email protected]")).thenReturn(true);
 
        assertThatThrownBy(() -> service.create(new CreateUserRequest("  [email protected] ", "pw")))
            .isInstanceOf(DuplicateResourceException.class);
 
        verify(encoder, never()).encode(any());          // fails if hashing happens before the duplicate check
        verify(users, never()).save(any());
    }
}
// fails if trim/toLowerCase is dropped (the stub won't match), or if the check and hash are reordered

Spring Boot 4 brings JUnit 6 and Mockito 5; the Jupiter API is unchanged. @MockBean is gone; use @MockitoBean. Other languages: Go uses table-driven tests and interface fakes; Jest has jest.fn().

Stubs, mocks, spies, fakes
Kind Purpose Mockito
Stub supply indirect input when(repo.exists(..)).thenReturn(true)
Mock check indirect output verify(repo).save(..), never()
Spy real object with a few methods overridden spy(real), doReturn(..).when(spy).m()
Fake a simple hand-written implementation with state InMemoryUserRepository

Use an ArgumentCaptor to check the saved object (hashed password, normalized email). Don't use lenient() to switch off strict stubs: an unused stub means the test no longer matches the code.

4. Working with AI

Give the AI: listing a method's branches and boundary values, AAA test skeletons, reading PIT reports and proposing tests for surviving mutants.

Check in AI-written code:

  • Each test names a line that, deleted or flipped, makes it fail.
  • Boundary values are present (threshold, threshold minus one, 0, empty, null).
  • Stubs use concrete values; any() only where it truly doesn't matter.
  • No mock(...) of records, DTOs, entities or the class under test.
  • No Instant.now() or Thread.sleep in tests.

5. Exercises

Exercise 1: "100% covered"

The AI tests boolean isEligible(long amount) { return amount >= 500_000; } and reports "100% line and branch coverage":

JAVA
@Test void smallOrderIsNotEligible() { assertThat(service.isEligible(100_000)).isFalse(); }
@Test void largeOrderIsEligible()    { assertThat(service.isEligible(1_000_000)).isTrue(); }

Which mutant survives? Add exactly the test you need.

Solution to Exercise 1

The ">= becomes >" mutant (PIT's conditional boundary) survives: 100_000 and 1_000_000 give the same result for both versions. Coverage is 100% because both branches run, but the threshold itself is never touched.

JAVA
@ParameterizedTest
@CsvSource({"499999, false", "500000, true"})
void eligibilityStartsExactlyAtThreshold(long amount, boolean expected) {
    assertThat(service.isEligible(amount)).isEqualTo(expected);
}

500000, true kills the > mutant; 499999, false kills a shifted-threshold mutant.

Exercise 2: A flaky test

tokenExpiresAfterSevenDays fails about 1 in 50 CI runs and passes on rerun: expected: false but was: true. The service calls Instant.now(); the test creates the token with Instant.now().plus(Duration.ofDays(7)). Diagnose and fix.

Solution to Exercise 2

The test and the service read the clock at two different moments; when CI is slow or GC pauses in between, the boundary comparison flips. Don't add retries to make it "green".

Fix: inject a Clock into the service (Clock.systemUTC() in production); tests use Clock.fixed(...) and Clock.offset(fixed, Duration.ofDays(8)) to cross the boundary deterministically; add a test exactly at expiresAt.

Summary

  • A test has value when it fails on wrong behavior.
  • Unit tests for decisions, slice/integration tests for wiring.
  • Stub concrete values; don't mock value objects.
  • Coverage doesn't measure a suite's strength; mutation testing does.
  • Time comes through an injected Clock.

Read more: Slice tests and Testcontainers.

Practice interview questions on this topic

All Testing questions →All AI & LLM questions →

Loading comments…