Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Can thenThrow() be used with custom exceptions


Can thenThrow() be used with custom exceptions


Yes, `thenThrow()` can be used with custom exceptions in Mockito. This method allows you to specify that a mock object should throw an exception when a particular method is called. Here's how you can use it with custom exceptions:

Using Custom Exceptions with `thenThrow()`

1. Define a Custom Exception: First, you need to define your custom exception class. This class should extend either `Exception` for checked exceptions or `RuntimeException` for unchecked exceptions.

java
   public class MyCustomException extends Exception {
       public MyCustomException(String message) {
           super(message);
       }
   }
   

2. Mocking with `thenThrow()`: Once you have your custom exception, you can use `thenThrow()` to specify that a mock object should throw this exception when a method is called.

For non-void methods, you use `when().thenThrow()`:

java
   import static org.mockito.Mockito.*;

   @Test
   void testThrowCustomException() {
       MyClass mockClass = mock(MyClass.class);
       when(mockClass.someMethod()).thenThrow(new MyCustomException("Custom error message"));
       assertThrows(MyCustomException.class, () -> {
           mockClass.someMethod();
       });
   }
   

For void methods, you use `doThrow().when()`:

java
   @Test
   void testThrowCustomExceptionInVoidMethod() {
       MyClass mockClass = mock(MyClass.class);
       doThrow(new MyCustomException("Custom error in void method")).when(mockClass).voidMethod();
       assertThrows(MyCustomException.class, () -> {
           mockClass.voidMethod();
       });
   }
   

3. Throwing Multiple Exceptions: You can also configure the mock to throw different exceptions on subsequent calls using `thenThrow()` multiple times:

java
   @Test
   void testThrowMultipleCustomExceptions() {
       MyClass mockClass = mock(MyClass.class);
       when(mockClass.someMethod())
           .thenThrow(new MyCustomException("First error"))
           .thenThrow(new MyCustomException("Second error"));
       assertThrows(MyCustomException.class, () -> {
           mockClass.someMethod(); // Throws "First error"
       });
       assertThrows(MyCustomException.class, () -> {
           mockClass.someMethod(); // Throws "Second error"
       });
   }
   

Benefits of Using Custom Exceptions

Using custom exceptions provides several benefits:
- Specificity: Custom exceptions can convey specific information about the error, making it easier to diagnose and handle.
- Flexibility: You can add custom attributes or methods to your exceptions, which can be useful for logging or displaying error messages.
- Readability: Custom exceptions improve code readability by clearly indicating the type of error that occurred, which is particularly useful in complex systems.

In summary, `thenThrow()` can be effectively used with custom exceptions in Mockito to simulate various error scenarios during unit testing, enhancing the robustness and reliability of your code.

Citations:
[1] https://www.browserstack.com/guide/mockito-throw-exception
[2] https://learn.microsoft.com/en-us/dotnet/standard/exceptions/best-practices-for-exceptions
[3] https://stackoverflow.com/questions/38852392/mockito-difference-between-thenthrowexception-class-and-thenthrownew-excepti
[4] https://howtodoinjava.com/java/exception-handling/best-practices-for-for-exception-handling/
[5] https://stackify.com/java-custom-exceptions/
[6] https://stackoverflow.com/questions/3762047/throw-checked-exceptions-from-mocks-with-mockito
[7] https://www.baeldung.com/mockito-exceptions
[8] https://rollbar.com/blog/cpp-custom-exceptions/