0
0
JUnittesting~10 mins

when().thenThrow() for exceptions in JUnit - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test uses when().thenThrow() to simulate an exception from a mocked service method. It verifies that the exception is correctly thrown and handled.

Test Code - JUnit 5 with Mockito
JUnit
import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;

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

class UserService {
    UserRepository repo;
    UserService(UserRepository repo) {
        this.repo = repo;
    }
    public String getUserName(int id) {
        return repo.findNameById(id);
    }
}

interface UserRepository {
    String findNameById(int id);
}

public class UserServiceTest {

    @Test
    void testGetUserNameThrowsException() {
        UserRepository mockRepo = Mockito.mock(UserRepository.class);
        when(mockRepo.findNameById(1)).thenThrow(new RuntimeException("User not found"));

        UserService service = new UserService(mockRepo);

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

        assertEquals("User not found", thrown.getMessage());
    }
}
Execution Trace - 5 Steps
StepActionSystem StateAssertionResult
1Create mock of UserRepositorymockRepo is a mock object with no behavior yet-PASS
2Stub mockRepo.findNameById(1) to throw RuntimeException("User not found")mockRepo configured to throw exception when findNameById(1) is called-PASS
3Create UserService instance with mockReposervice uses mockRepo internally-PASS
4Call service.getUserName(1) inside assertThrowsservice calls mockRepo.findNameById(1), which throws RuntimeExceptionassertThrows verifies RuntimeException is thrownPASS
5Check exception message equals "User not found"exception caught with message "User not found"assertEquals verifies exception messagePASS
Failure Scenario
Failing Condition: Mock not configured to throw exception or method called with wrong argument
Execution Trace Quiz - 3 Questions
Test your understanding
What does when().thenThrow() do in this test?
AIt verifies that an exception was thrown.
BIt makes the mock method throw an exception when called with specific arguments.
CIt catches exceptions thrown by the real method.
DIt prevents the method from being called.
Key Result
Use when().thenThrow() to simulate exceptions from dependencies and assertThrows to verify your code handles them properly.