Lançando exceções e fazendo chamadas consecutivas
Configure objetos simulados para lançar exceções e retornar valores diferentes em invocações consecutivas, criando cenários de teste mais completos.
Lançando exceções e fazendo chamadas consecutivas é 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.
Beyond Simple Returns
Stubbing return values covers the happy path, but real code must also handle errors and changing state. Mockito lets you stub mocks to throw exceptions and to vary their answers per call.
thenThrow Basics
Use thenThrow to make a stubbed method raise an exception, so you can test your error handling.
when(repo.findById(99L))
.thenThrow(new NotFoundException());Testing the Failure Path
Combine the throwing stub with assertThrows to verify your code reacts correctly.
@Test
void propagatesError() {
when(repo.findById(99L)).thenThrow(new NotFoundException());
assertThrows(NotFoundException.class,
() -> service.load(99L));
}Throwing from void Methods
For void methods you cannot use when(...) directly. Use doThrow(...).when(mock).method() instead.
doThrow(new IllegalStateException())
.when(logger).flush();Consecutive Return Values
Pass multiple arguments to thenReturn to return different values on successive calls. The last value repeats once exhausted.
when(counter.next())
.thenReturn(1, 2, 3);Chaining Stub Calls
You can also chain calls. Each call describes the next invocation in order.
when(counter.next())
.thenReturn(1)
.thenReturn(2)
.thenThrow(new IllegalStateException());Mixing Returns and Throws
A common pattern: succeed a few times, then fail. This models flaky resources like a retrying network client.
when(client.fetch())
.thenReturn("ok")
.thenThrow(new IOException("down"));Checked Exceptions Caveat
A mock can only throw a checked exception that the stubbed method declares. Throwing an undeclared checked exception causes a runtime error from Mockito.
doReturn for Consecutive Values
The do* family also supports chaining and is required when stubbing spies or void methods.
doReturn("a")
.doReturn("b")
.when(provider).value();Why This Matters
Exception and consecutive stubbing let you exercise retry logic, fallback paths, and stateful sequences without building complex fake objects.
Putting It Together
You can now drive a mock through a full sequence of success and failure to validate resilient code.
when(api.call())
.thenReturn("first")
.thenThrow(new TimeoutException());Quick Check
How do you make a stubbed method return 1, then 2 on its second call?
Recap
You learned advanced stubbing:
thenThrow/doThrowsimulate errors- Multiple
thenReturnargs or chains give consecutive values - Mocks can only throw declared checked exceptions
- Use
do*for void methods and spies
Perguntas Frequentes
A aula “Lançando exceções e fazendo chamadas consecutivas” é grátis?
Sim — o texto completo de “Lançando exceções e fazendo chamadas consecutivas” é 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 “Lançando exceções e fazendo chamadas consecutivas”?
Configure objetos simulados para lançar exceções e retornar valores diferentes em invocações consecutivas, criando cenários de teste mais completos. 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 “Lançando exceções e fazendo chamadas consecutivas”?
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
- Configurando Valores de Retorno
- Correspondedores de Argumentos do Mockito
- Espionando Objetos Reais
- Lançando exceções e fazendo chamadas consecutivas