0
0
JUnittesting~5 mins

when().thenThrow() for exceptions in JUnit

Choose your learning style9 modes available
Introduction

We use when().thenThrow() to tell a test to expect an error from a specific action. This helps us check if our code handles problems correctly.

When you want to test how your code reacts to a failure from a service or method.
When you want to simulate an error like a network failure or invalid input in a test.
When you want to make sure your program throws the right exception in bad situations.
Syntax
JUnit
when(mockedObject.methodCall()).thenThrow(new ExceptionType("message"));

when() sets up the method call you want to fake.

thenThrow() tells the test to throw the exception when that method is called.

Examples
This makes getData() throw a RuntimeException with a message.
JUnit
when(service.getData()).thenThrow(new RuntimeException("Error occurred"));
This makes findById(1) throw an IllegalArgumentException.
JUnit
when(repository.findById(1)).thenThrow(new IllegalArgumentException("Invalid ID"));
Sample Program

This test creates a fake UserRepository that throws an exception when findById(1) is called. The test checks that getUser(1) throws the same exception with the correct message.

JUnit
import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.Test;

class UserService {
    UserRepository repo;
    UserService(UserRepository repo) {
        this.repo = repo;
    }
    User getUser(int id) {
        return repo.findById(id);
    }
}

interface UserRepository {
    User findById(int id);
}

class User {}

public class UserServiceTest {
    @Test
    void testGetUserThrowsException() {
        UserRepository mockRepo = mock(UserRepository.class);
        when(mockRepo.findById(1)).thenThrow(new RuntimeException("User not found"));

        UserService service = new UserService(mockRepo);

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

        assertEquals("User not found", thrown.getMessage());
    }
}
OutputSuccess
Important Notes

Always mock only the methods you need to test exceptions for.

Use assertThrows to check the exception type and message.

Summary

when().thenThrow() helps simulate errors in tests.

It is useful to check how your code handles exceptions.

Use it with assertThrows to verify the exception is thrown correctly.