How can I use Mockito to mock and assert a thrown exception in a JUnit test?

How can I use Mockito to mock and assert a thrown exception in a JUnit test? Specifically, how can I set up Mockito to expect an exception and verify that it is thrown correctly?

You can use Mockito.when to specify that a method should throw an exception when called, and then use JUnit’s assertThrows to verify that the exception is thrown.

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

@Test
void testMethodThrowsException() {
    // Arrange
    MyClass myClass = mock(MyClass.class);
    when(myClass.myMethod()).thenThrow(new RuntimeException("Exception message"));

    // Act & Assert
    RuntimeException thrown = assertThrows(RuntimeException.class, () -> {
        myClass.myMethod();
    });
    assertEquals("Exception message", thrown.getMessage());
}

If you are dealing with a void method, you should use Mockito.doThrow to specify that an exception should be thrown when the method is invoked.

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

@Test
void testVoidMethodThrowsException() {
    // Arrange
    MyClass myClass = mock(MyClass.class);
    doThrow(new RuntimeException("Exception message")).when(myClass).voidMethod();

    // Act & Assert
    RuntimeException thrown = assertThrows(RuntimeException.class, () -> {
        myClass.voidMethod();
    });
    assertEquals("Exception message", thrown.getMessage());
}

You can also verify that a method was called and threw an exception using Mockito.verify along with assertThrows.

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

@Test
void testExceptionVerification() {
    // Arrange
    MyClass myClass = mock(MyClass.class);
    when(myClass.myMethod()).thenThrow(new RuntimeException("Exception message"));

    // Act & Assert
    RuntimeException thrown = assertThrows(RuntimeException.class, () -> {
        myClass.myMethod();
    });

    verify(myClass).myMethod(); // Verify the method was called
    assertEquals("Exception message", thrown.getMessage());
}