@Mockと@InjectMocksによるモックの注入
Mockitoのアノテーションを使ってテスト対象クラスへモック化した依存関係を注入し、セットアップコードの定型処理を減らします。
「@Mockと@InjectMocksによるモックの注入」はCoddyKit上の無料Testing Mastery: JUnit, Mockito & Integration Testsレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応の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時間対応のAIチューター)、Testing Mastery: JUnit, Mockito & Integration Testsコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Testing Mastery: JUnit, Mockito & Integration Testsコースには全4レッスンが含まれています。
「@Mockと@InjectMocksによるモックの注入」で何を学びますか?
Mockitoのアノテーションを使ってテスト対象クラスへモック化した依存関係を注入し、セットアップコードの定型処理を減らします。 ブラウザで直接実行するハンズオンコードでTesting Mastery: JUnit, Mockito & Integration Testsを演習し、24時間対応の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フィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- Mock、Stub、Fake
- MockitoでMockを作成する
- Mockのインタラクションを検証する
- @Mockと@InjectMocksによるモックの注入