Mockito handles checked and unchecked exceptions differently, primarily due to how Java treats these exceptions and how Mockito is designed to work with method signatures.
Checked Exceptions
- Definition: Checked exceptions are exceptions that are checked at compile time. They must be either caught in a `try-catch` block or declared in the method signature using the `throws` keyword[3].
- Mockito Handling: Mockito allows throwing checked exceptions from a mock object only if the exception is declared in the method signature. If you attempt to throw a checked exception that is not declared, Mockito will throw a `MockitoException` with a message indicating that the checked exception is invalid for that method[1][2]. For example, if a method `void someMethod() throws IOException`, you can use Mockito to throw an `IOException` without issues.
Unchecked Exceptions
- Definition: Unchecked exceptions are exceptions that are not checked at compile time. They are typically runtime exceptions or errors that indicate programming errors[3].
- Mockito Handling: Mockito can easily handle unchecked exceptions without any restrictions. You can use `thenThrow()` or `doThrow()` to simulate unchecked exceptions like `RuntimeException` or `NullPointerException` without needing them to be declared in the method signature[1][2]. This makes it straightforward to test error handling for unexpected conditions.
Workarounds for Checked Exceptions
If you need to throw a checked exception that is not declared in the method signature, you can use Mockito's `doAnswer()` method. This method allows you to define custom behavior for a mock method, including throwing exceptions that are not declared in the method signature[4]. However, this approach requires more manual handling and is generally less straightforward than using `thenThrow()` or `doThrow()`.
In summary, Mockito's handling of checked exceptions is more restrictive because it adheres to Java's compile-time checks, while unchecked exceptions can be thrown freely, making them easier to use in tests.
Citations:[1] https://blog.sammkinng.in/blogs/checked-exception-is-invalid-for-this-method
[2] https://www.toptal.com/java/a-guide-to-everyday-mockito
[3] https://rollbar.com/blog/how-to-handle-checked-unchecked-exceptions-in-java/
[4] https://stackoverflow.com/questions/3762047/throw-checked-exceptions-from-mocks-with-mockito
[5] https://stackoverflow.com/questions/38852392/mockito-difference-between-thenthrowexception-class-and-thenthrownew-excepti
[6] https://www.reddit.com/r/java/comments/1cct4iq/if_everyone_hates_checked_exceptions_wheres_the/
[7] https://www.janbasktraining.com/community/java/throw-checked-exceptions-from-mocks-with-mockito
[8] https://www.youtube.com/watch?v=6-gj2W2ycMI
[9] https://www.browserstack.com/guide/mockito-throw-exception