In Mockito, throwing checked exceptions from mocks can be accomplished using the thenThrow method. Here's a step-by-step guide on how to achieve this:
Step-by-Step Guide
Set Up Mockito and Dependencies
org.mockito
mockito-core
4.0.0
test
Ensure you have Mockito in your project. If you are using Maven, include the following dependency in your pom.xml:
For Gradle, add the following to your build.gradle:
testImplementation 'org.mockito:mockito-core:4.0.0' // Use the latest version
Create a Mock and Configure It to Throw an Exception
Use the when and thenThrow methods to specify that a mock should throw a checked exception.
Here’s an example of a service method that throws an IOException:
import static org.mockito.Mockito.*;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.io.IOException;
public class MyServiceTest {
public class MyService {
public void performAction() throws IOException {
// Actual implementation
}
}
@Test
public void testPerformActionThrowsIOException() throws IOException {
// Create a mock instance of MyService
MyService myServiceMock = mock(MyService.class);
// Configure the mock to throw IOException when performAction is called
doThrow(new IOException("IO error")).when(myServiceMock).performAction();
// Use the mock in your test
try {
myServiceMock.performAction();
} catch (IOException e) {
// Verify the exception
assertEquals("IO error", e.getMessage());
}
}
}
Using when with Methods that Return Values
If you have a method that returns a value and you want to throw an exception, use the when syntax:
import static org.mockito.Mockito.*;
import org.junit.jupiter.api.Test;
import java.io.IOException;
public class MyServiceTest {
public interface MyService {
String getData() throws IOException;
}
@Test
public void testGetDataThrowsIOException() throws IOException {
// Create a mock instance of MyService
MyService myServiceMock = mock(MyService.class);
// Configure the mock to throw IOException when getData is called
when(myServiceMock.getData()).thenThrow(new IOException("IO error"));
// Use the mock in your test
try {
myServiceMock.getData();
} catch (IOException e) {
// Verify the exception
assertEquals("IO error", e.getMessage());
}
}
}
Summary
- Use doThrow for void methods to throw checked exceptions.
- Use when(...).thenThrow for methods that return values to throw checked exceptions.
- Ensure your test captures and asserts the expected exception.
These techniques will allow you to simulate and test the behavior of your code when checked exceptions are thrown, enabling more robust and comprehensive unit tests.