Lanzamiento de excepciones y llamadas consecutivas
Configure mocks para lanzar excepciones y devolver valores diferentes en invocaciones consecutivas, creando escenarios de prueba más completos.
Lanzamiento de excepciones y llamadas consecutivas es una lección gratuita de Testing Mastery: JUnit, Mockito & Integration Tests en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Testing Mastery: JUnit, Mockito & Integration Tests, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Testing Mastery: JUnit, Mockito & Integration Tests incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en 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
Preguntas frecuentes
¿La lección «Lanzamiento de excepciones y llamadas consecutivas» es gratis?
Sí — el texto completo de «Lanzamiento de excepciones y llamadas consecutivas» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Testing Mastery: JUnit, Mockito & Integration Tests, actualiza a CoddyKit PRO. El curso de Testing Mastery: JUnit, Mockito & Integration Tests incluye 4 lecciones en total.
¿Qué aprenderé en «Lanzamiento de excepciones y llamadas consecutivas»?
Configure mocks para lanzar excepciones y devolver valores diferentes en invocaciones consecutivas, creando escenarios de prueba más completos. Practicas Testing Mastery: JUnit, Mockito & Integration Tests con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Testing Mastery: JUnit, Mockito & Integration Tests?
No se requiere experiencia previa. Testing Mastery: JUnit, Mockito & Integration Tests en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.
¿Cuánto tiempo toma la lección «Lanzamiento de excepciones y llamadas consecutivas»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Testing Mastery: JUnit, Mockito & Integration Tests?
Sí. Cada lección de Testing Mastery: JUnit, Mockito & Integration Tests incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Configuración de valores de retorno
- Matchers de argumentos de Mockito
- Espionaje de objetos reales
- Lanzamiento de excepciones y llamadas consecutivas