Files
2nd/10_Wiki/Topics/Architecture/Mockito.md
T
Antigravity Agent f8b21af4be Wiki cleanup: error-doc removal, dedup merge, link normalization
10_Wiki/Topics 대규모 정리:
- 오류 캡처/미완성 stub 문서 227개 제거
- 교차폴더 중복 43클러스터 병합 (63파일 → redirect)
- 링크명 정규화: 깨진 링크 수정·redirect 직결·개념 매핑 ~2,400건
- 카테고리 MOC 6개 신규 생성
- Graph 섹션 미해결 related-keyword 링크 10,058건 제거

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 23:52:15 +09:00

4.8 KiB

id, title, category, status, canonical_id, aliases, duplicate_of, source_trust_level, confidence_score, verification_status, tags, raw_sources, last_reinforced, github_commit, tech_stack
id title category status canonical_id aliases duplicate_of source_trust_level confidence_score verification_status tags raw_sources last_reinforced github_commit tech_stack
wiki-2026-0508-mockito Mockito 10_Wiki/Topics verified self
Java Mocking
Mockito Framework
none A 0.9 applied
java
testing
mocking
junit
2026-05-10 pending
language framework
java mockito-junit5

Mockito

매 한 줄

"매 mock = 매 collaborator 의 stub + verify". Java testing 의 매 de facto mocking framework. JUnit 5 + Mockito 5.x 의 매 standard combo. 2026 modern Java (21 LTS / 25) 매 record + sealed type 와 호환.

매 핵심

매 capability

  • Stub: 매 method 의 fake return value.
  • Verify: 매 interaction 의 assertion (called N times, with args).
  • Spy: 매 real object 의 partial mock.
  • Argument captor: 매 invocation arg 의 capture, inspect.

매 lifecycle

  • @Mock — 매 dependency.
  • @InjectMocks — 매 system under test.
  • @ExtendWith(MockitoExtension.class) — JUnit 5 integration.
  • mockStatic — 매 static method.

매 응용

  1. Service unit test: 매 repository 의 mock.
  2. Controller test: 매 service 의 stub + slice test.
  3. Integration boundary: 매 external API 의 mock.

💻 패턴

Basic stub + verify

import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;

@ExtendWith(MockitoExtension.class)
class OrderServiceTest {
    @Mock OrderRepository repo;
    @Mock PaymentGateway gateway;
    @InjectMocks OrderService service;

    @Test
    void placesOrder() {
        when(repo.save(any(Order.class))).thenAnswer(inv -> inv.getArgument(0));
        when(gateway.charge(anyLong(), anyString())).thenReturn(new Receipt("rcpt-1"));

        Order o = service.place(new Cart(List.of(item("sku", 1000))), "card-1");

        assertEquals("rcpt-1", o.receiptId());
        verify(repo).save(any(Order.class));
        verify(gateway, times(1)).charge(1000L, "card-1");
    }
}

Argument captor

@Captor ArgumentCaptor<Order> orderCaptor;

@Test
void persistsCorrectAmount() {
    service.place(cart, "card-1");
    verify(repo).save(orderCaptor.capture());
    assertEquals(1500L, orderCaptor.getValue().total());
}

Spy (partial mock)

@Test
void spyExample() {
    List<String> real = new ArrayList<>();
    List<String> spy = spy(real);
    spy.add("a");
    doReturn(99).when(spy).size(); // override
    assertEquals(99, spy.size());
    verify(spy).add("a");
}

Static mock

@Test
void staticMock() {
    try (MockedStatic<Clock> m = mockStatic(Clock.class)) {
        m.when(Clock::systemUTC).thenReturn(Clock.fixed(Instant.EPOCH, ZoneOffset.UTC));
        assertEquals(Instant.EPOCH, Clock.systemUTC().instant());
    }
}

Throw exception

when(gateway.charge(anyLong(), anyString()))
    .thenThrow(new PaymentDeclinedException("insufficient"));

assertThrows(PaymentDeclinedException.class,
    () -> service.place(cart, "card-1"));

Multiple return values

when(repo.findById(1L))
    .thenReturn(Optional.empty())
    .thenReturn(Optional.of(new Order(1L)));

assertTrue(service.fetch(1L).isEmpty());
assertTrue(service.fetch(1L).isPresent());

BDD style

import static org.mockito.BDDMockito.*;

@Test
void bdd() {
    given(repo.findById(1L)).willReturn(Optional.of(new Order(1L)));
    Order o = service.fetch(1L).orElseThrow();
    then(repo).should().findById(1L);
    assertEquals(1L, o.id());
}

Verify no more interactions

verify(repo).save(any());
verifyNoMoreInteractions(repo);
verifyNoInteractions(gateway); // never called

매 결정 기준

상황 Approach
Pure Java unit test Mockito + JUnit 5
Spring boot slice Mockito + @MockBean (Spring Boot 3.x: @MockitoBean)
Integration test Testcontainers, no mock
Static legacy code mockStatic (try-with-resources)

기본값: Mockito 5.x + JUnit 5 + AssertJ.

🔗 Graph

🤖 LLM 활용

언제: 매 stub setup boilerplate 의 generate, verify assertion 의 propose, captor pattern 의 explain. 언제 X: 매 test design, what to mock vs integration-test — design judgment.

안티패턴

  • Mock everything: 매 value object 의 mock = brittle test.
  • Over-verify: 매 internal call 의 verify = refactor 의 break.
  • Mock 의 your own mock: cascade mock = smell. Refactor SUT.
  • No MockitoExtension: stub 의 strict mode 의 lose.

🧪 검증 / 중복

  • Verified (Mockito official docs, Effective Unit Testing by Koskela, Mockito 5.x release notes).
  • 신뢰도 A.

🕓 Changelog

날짜 변경
2026-05-08 Phase 1
2026-05-10 Manual cleanup — Mockito 5 + JUnit 5 patterns for modern Java