Mockito BDDMockito willThrow() Method Example

1. Introduction

In Behavior-Driven Development (BDD), setting up expected behaviors includes not just the regular return values but also the exceptions that may be thrown during the execution. BDDMockito, the BDD variant of Mockito, offers the willThrow() method, allowing us to simulate exceptions for given conditions. This is particularly useful for testing how our code handles unexpected scenarios.

2. Example Steps

1. Create a service class that can potentially throw an exception.

2. Set up a JUnit test class.

3. Use BDDMockito's willThrow() method to simulate an exception for a specific mock condition.

4. Run the test and verify if the exception is thrown as expected.

3. Mockito BDDMockito willThrow() Method Example

// Step 1: Define a service with a potential exception
class DocumentService {
    public void saveDocument(String content) {
        // A stub implementation

// Step 2: Set up a JUnit test class
import org.junit.jupiter.api.Test;
import static org.mockito.BDDMockito.*;
import static org.junit.jupiter.api.Assertions.assertThrows;

public class DocumentServiceTest {

    public void testSaveDocumentException() {
        // Mock the DocumentService using BDDMockito
        DocumentService mockService = mock(DocumentService.class);

        // Step 3: Use BDDMockito's willThrow() method
        given(mockService.saveDocument("faultyContent")).willThrow(new IllegalArgumentException("Document content is not valid"));

        // Execute the test and expect the exception
        assertThrows(IllegalArgumentException.class, () -> mockService.saveDocument("faultyContent"));


Exception in thread "main" java.lang.IllegalArgumentException: Document content is not valid

4. Step By Step Explanation

1. We started with a DocumentService class that has a method saveDocument(). In this example, it's just a stub with no actual implementation.

2. In the DocumentServiceTest test class, we mock the DocumentService.

3. Using BDDMockito's willThrow() method, we set up our mock to throw an IllegalArgumentException with a specific message when saveDocument("faultyContent") is called.

4. The JUnit's assertThrows() method is then used to verify that our mock indeed throws the expected exception. As per our setup, invoking saveDocument("faultyContent") on the mock instance throws the specified IllegalArgumentException.