@Mock과 @InjectMocks로 모의 객체 주입하기
Mockito 어노테이션을 사용하여 테스트 대상 클래스에 모의 의존성을 연결하고, 반복적인 설정 코드를 줄이세요.
@Mock과 @InjectMocks로 모의 객체 주입하기은(는) CoddyKit의 무료 Testing Mastery: JUnit, Mockito & Integration Tests 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Testing Mastery: JUnit, Mockito & Integration Tests 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Testing Mastery: JUnit, Mockito & Integration Tests 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Why Annotations?
Creating mocks manually with mock(Type.class) works, but for classes with several dependencies it becomes repetitive. Mockito offers annotations that declare and wire mocks for you.
@Mockdeclares a mock field@InjectMocksbuilds the real object and injects the mocks
The Class Under Test
Imagine an OrderService that depends on a PaymentGateway. We want to test the service while controlling the gateway.
class OrderService {
private final PaymentGateway gateway;
OrderService(PaymentGateway gateway) { this.gateway = gateway; }
boolean checkout(double amount) {
return gateway.charge(amount);
}
}Declaring a @Mock
Annotate a field with @Mock and Mockito creates a mock instance for it automatically once the annotations are processed.
@Mock
PaymentGateway gateway;Using @InjectMocks
@InjectMocks tells Mockito to instantiate the target and inject any @Mock fields into it, via constructor, setter, or field injection.
@Mock PaymentGateway gateway;
@InjectMocks OrderService service;Activating the Annotations
Annotations do nothing on their own. With JUnit 5 you enable them using @ExtendWith(MockitoExtension.class) on the test class.
@ExtendWith(MockitoExtension.class)
class OrderServiceTest {
@Mock PaymentGateway gateway;
@InjectMocks OrderService service;
}The Older openMocks Approach
Without the extension you can call MockitoAnnotations.openMocks(this) in a @BeforeEach method. Prefer the extension when you can.
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
}Writing the Test
Now stub the injected mock and exercise the service. The service already holds the mocked gateway, so no manual wiring is needed.
@Test
void checkoutSucceeds() {
when(gateway.charge(100.0)).thenReturn(true);
assertTrue(service.checkout(100.0));
}Injection Strategies
Mockito tries injection in this order:
- Constructor injection (preferred)
- Setter injection
- Field injection
Constructor injection is the safest because it works with final fields.
Multiple Dependencies
A class with several collaborators just gets several @Mock fields. Mockito matches each by type during injection.
@Mock PaymentGateway gateway;
@Mock InventoryRepo inventory;
@InjectMocks OrderService service;When Injection Fails Silently
If a dependency cannot be matched, the field stays null rather than throwing. A NullPointerException at test time often means injection did not happen as expected. Verify types and constructor signatures.
Cleaner Tests
Annotations remove repetitive mock(...) and new Service(...) calls, keeping each test focused on behavior instead of wiring.
Quick Check
Which annotation builds the real object and injects mocks into it?
Recap
You learned to wire mocks declaratively:
@Mockdeclares a mock field@InjectMocksbuilds the target and injects mocks- Enable with
@ExtendWith(MockitoExtension.class) - Constructor injection is preferred and supports final fields
자주 묻는 질문
“@Mock과 @InjectMocks로 모의 객체 주입하기” 강의는 무료인가요?
네 — “@Mock과 @InjectMocks로 모의 객체 주입하기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Testing Mastery: JUnit, Mockito & Integration Tests 강의 전체를 잠금 해제할 수 있습니다. Testing Mastery: JUnit, Mockito & Integration Tests 강의에는 총 4개의 강의가 포함되어 있습니다.
“@Mock과 @InjectMocks로 모의 객체 주입하기”에서 뭘 배우나요?
Mockito 어노테이션을 사용하여 테스트 대상 클래스에 모의 의존성을 연결하고, 반복적인 설정 코드를 줄이세요. 브라우저에서 직접 실행하는 실습 코드로 Testing Mastery: JUnit, Mockito & Integration Tests을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Testing Mastery: JUnit, Mockito & Integration Tests을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Testing Mastery: JUnit, Mockito & Integration Tests은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.
“@Mock과 @InjectMocks로 모의 객체 주입하기” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Testing Mastery: JUnit, Mockito & Integration Tests 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Testing Mastery: JUnit, Mockito & Integration Tests 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 목, 스텁, 페이크
- Mockito로 목 만들기
- 목 상호 작용 검증
- @Mock과 @InjectMocks로 모의 객체 주입하기