Mockito How to mock and assert a thrown exception?

To mock and assert a thrown exception in Mockito, you can use the doThrow() method and the verify() method.

Here's an example of how you can use these methods to mock and assert a thrown exception:

import static org.mockito.Mockito.*;

// Create a mock
Foo mock = mock(Foo.class);

// Set up the mock to throw an exception when the foo() method is called
doThrow(new RuntimeException("error"))
    .when(mock)
    .foo();

// Invoke the foo() method on the mock
try {
  mock.foo();
  fail("Expected exception was not thrown");
} catch (RuntimeException e) {
  // Verify that the foo() method was called on the mock
  verify(mock).foo();
  // Assert that the exception message is correct
  assertEquals("error", e.getMessage());
}

In this example, the doThrow() method is used to set up the mock to throw a RuntimeException with the message "error" when the foo() method is called. The verify() method is then used to verify that the foo() method was called on the mock. Finally, the exception is caught and the message is asserted to be "error".

This is just one way of mocking and asserting a thrown exception in Mockito. There are other ways you can do this, depending on your specific needs and the version of Mockito you are using.