How can you simulate an exception being thrown in Mockito?
A) Using when().thenThrow()
B) Using verify().thenThrow()
C) Using mock().throw()
D) Using assert().throw()
Answer:
A) Using when().thenThrow()
Explanation:
In Mockito, you can simulate an exception being thrown using the when().thenThrow()
method. This is useful when you want to test how your code handles exceptions thrown by its dependencies.
For example:
when(mockObject.someMethod()).thenThrow(new RuntimeException("Exception message"));
In this example, when someMethod()
is called on mockObject
, a RuntimeException
with the message “Exception message” will be thrown. This allows you to test the exception-handling logic in your code.