Mockito.doThrow() Example

1. Introduction

Mockito provides a plethora of methods to aid in the mocking and stubbing of object behavior. Among them is the doThrow() method, which allows users to stub a specific exception to be thrown when a mocked method is called. This becomes especially handy when you want to simulate error scenarios in your tests, ensuring that your code can gracefully handle them.

2. Example Steps

1. Create an interface with a method that can potentially throw an exception.

2. Provide a concrete implementation of this interface.

3. Set up a test class.

4. Mock the interface with Mockito.

5. Use the doThrow() method to stub an exception for the mocked method.

6. Invoke the method and handle the stubbed exception.

3. Mockito.doThrow() Example

import org.junit.jupiter.api.Test;
import static org.mockito.Mockito.*;

// Step 1: Define an interface
interface FileService {
    void deleteFile(String path) throws Exception;

// Step 2: Concrete implementation of the interface
class RealFileService implements FileService {
    public void deleteFile(String path) {
        // Some real deletion logic here
        System.out.println("File deleted from: " + path);

public class FileServiceTest {

    public void testDoThrowWithMockito() {
        // Step 4: Mock the FileService interface
        FileService mockedFileService = mock(FileService.class);

        // Step 5: Use doThrow() to stub an exception for deleteFile()
        doThrow(new RuntimeException("File not found!")).when(mockedFileService).deleteFile(anyString());

        try {
            // Invoke the method
        } catch (Exception e) {
            // Step 6: Handle the stubbed exception
            System.out.println("Caught exception: " + e.getMessage());


Caught exception: File not found!

4. Step By Step Explanation

1. Initially, we define a FileService interface with a method named deleteFile that can potentially throw an exception.

2. The RealFileService class offers an actual implementation, where a file would be deleted based on its path.

3. For testing, we have the FileServiceTest class. Inside this class, we mock the FileService interface to control its behavior.

4. Using the doThrow() method, we set up our mock to throw a RuntimeException with the message "File not found!" when deleteFile() is called.

5. We then try to call the deleteFile() method on the mock. As expected, the stubbed exception is thrown.

6. In the catch block, we print out the exception message. The beauty of this approach is that we can simulate and test how our code responds to different exception scenarios.