0
0
JUnittesting~15 mins

when().thenThrow() for exceptions in JUnit - Build an Automation Script

Choose your learning style9 modes available
Verify method throws exception using when().thenThrow() in JUnit with Mockito
Preconditions (3)
Step 1: Mock the dependency that the service class uses
Step 2: Use when().thenThrow() to simulate an exception when the method is called
Step 3: Call the service method that uses the mocked dependency
Step 4: Catch the exception or use assertion to verify the exception is thrown
✅ Expected Result: The test should pass if the expected exception is thrown when the method is called
Automation Requirements - JUnit 5 with Mockito
Assertions Needed:
Assert that the expected exception is thrown using assertThrows
Best Practices:
Use @ExtendWith(MockitoExtension.class) to enable Mockito in JUnit 5
Use explicit exception assertion with assertThrows instead of try-catch
Mock only the dependencies, not the class under test
Use descriptive method names for test clarity
Automated Solution
JUnit
import static org.mockito.Mockito.when;
import static org.junit.jupiter.api.Assertions.assertThrows;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

class Dependency {
    String getData() {
        return "real data";
    }
}

class Service {
    private final Dependency dependency;

    Service(Dependency dependency) {
        this.dependency = dependency;
    }

    String fetchData() {
        return dependency.getData();
    }
}

@ExtendWith(MockitoExtension.class)
public class ServiceTest {

    @Mock
    Dependency dependency;

    @InjectMocks
    Service service;

    @Test
    void fetchData_shouldThrowException_whenDependencyThrows() {
        when(dependency.getData()).thenThrow(new RuntimeException("Dependency failure"));

        RuntimeException thrown = assertThrows(RuntimeException.class, () -> {
            service.fetchData();
        });

        // Optional: verify exception message
        org.junit.jupiter.api.Assertions.assertEquals("Dependency failure", thrown.getMessage());
    }
}

This test uses Mockito to mock the Dependency class. The when().thenThrow() method tells Mockito to throw a RuntimeException when getData() is called.

The assertThrows method from JUnit 5 checks that the exception is actually thrown when service.fetchData() is called. This is cleaner and clearer than using try-catch blocks.

Annotations @Mock and @InjectMocks set up the test objects automatically. The @ExtendWith(MockitoExtension.class) enables Mockito support in JUnit 5.

This approach ensures the test fails if the exception is not thrown, making the test reliable and easy to understand.

Common Mistakes - 4 Pitfalls
{'mistake': 'Not using assertThrows and instead using try-catch to check exceptions', 'why_bad': 'Try-catch makes tests longer and less clear. It can also hide failures if assertions are missed.', 'correct_approach': "Use JUnit 5's assertThrows to clearly and concisely assert exceptions."}
Mocking the class under test instead of its dependencies
Not initializing Mockito annotations with @ExtendWith(MockitoExtension.class)
Using generic Exception instead of specific exception types
Bonus Challenge

Now add data-driven testing with 3 different exceptions thrown by the dependency

Show Hint