--- id: wiki-2026-0508-mockito title: Mockito category: 10_Wiki/Topics status: verified canonical_id: self aliases: [Java Mocking, Mockito Framework] duplicate_of: none source_trust_level: A confidence_score: 0.9 verification_status: applied tags: [java, testing, mocking, junit] raw_sources: [] last_reinforced: 2026-05-10 github_commit: pending tech_stack: language: java framework: 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 ```java 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 ```java @Captor ArgumentCaptor orderCaptor; @Test void persistsCorrectAmount() { service.place(cart, "card-1"); verify(repo).save(orderCaptor.capture()); assertEquals(1500L, orderCaptor.getValue().total()); } ``` ### Spy (partial mock) ```java @Test void spyExample() { List real = new ArrayList<>(); List spy = spy(real); spy.add("a"); doReturn(99).when(spy).size(); // override assertEquals(99, spy.size()); verify(spy).add("a"); } ``` ### Static mock ```java @Test void staticMock() { try (MockedStatic m = mockStatic(Clock.class)) { m.when(Clock::systemUTC).thenReturn(Clock.fixed(Instant.EPOCH, ZoneOffset.UTC)); assertEquals(Instant.EPOCH, Clock.systemUTC().instant()); } } ``` ### Throw exception ```java when(gateway.charge(anyLong(), anyString())) .thenThrow(new PaymentDeclinedException("insufficient")); assertThrows(PaymentDeclinedException.class, () -> service.place(cart, "card-1")); ``` ### Multiple return values ```java 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 ```java 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 ```java 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 - 부모: [[Unit-Testing]] · [[Test-Doubles]] ## 🤖 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 |