Injetando objetos simulados com @Mock e @InjectMocks
Use as anotações do Mockito para conectar dependências simuladas à classe em teste, reduzindo o código repetitivo de configuração.
Injetando objetos simulados com @Mock e @InjectMocks é uma aula grátis de Testing Mastery: JUnit, Mockito & Integration Tests no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Testing Mastery: JUnit, Mockito & Integration Tests, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Testing Mastery: JUnit, Mockito & Integration Tests inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
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
Perguntas Frequentes
A aula “Injetando objetos simulados com @Mock e @InjectMocks” é grátis?
Sim — o texto completo de “Injetando objetos simulados com @Mock e @InjectMocks” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Testing Mastery: JUnit, Mockito & Integration Tests, atualize para CoddyKit PRO. O curso de Testing Mastery: JUnit, Mockito & Integration Tests inclui 4 aulas no total.
O que vou aprender em “Injetando objetos simulados com @Mock e @InjectMocks”?
Use as anotações do Mockito para conectar dependências simuladas à classe em teste, reduzindo o código repetitivo de configuração. Você pratica Testing Mastery: JUnit, Mockito & Integration Tests com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Testing Mastery: JUnit, Mockito & Integration Tests?
Nenhuma experiência prévia é necessária. Testing Mastery: JUnit, Mockito & Integration Tests no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.
Quanto tempo leva a aula “Injetando objetos simulados com @Mock e @InjectMocks”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Testing Mastery: JUnit, Mockito & Integration Tests?
Sim. Cada aula de Testing Mastery: JUnit, Mockito & Integration Tests inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Mocks, Stubs e Fakes
- Criando Mocks com Mockito
- Verificando Interações com Mocks
- Injetando objetos simulados com @Mock e @InjectMocks