Introduction
In this chapter, we will learn about stubbing methods with exceptions using Mockito. Stubbing with exceptions allows you to simulate error conditions and test how your code handles them. This is useful for ensuring that your code can gracefully handle unexpected situations.
What is Stubbing?
Stubbing is the process of specifying what mock objects should do when their methods are called. By defining the behavior of mock objects, you can control their interactions and ensure that your tests are reliable and predictable. Stubbing allows you to return specific values, throw exceptions, or execute custom logic when a method is called.
Stubbing with Exceptions
Stubbing with exceptions allows you to specify that a method should throw an exception when called. This is useful for testing error handling and ensuring that your code can gracefully handle unexpected conditions.
Example: CalculatorService Class and CalculatorServiceTest Class
Class Under Test: CalculatorService
public class CalculatorService {
public int divide(int a, int b) {
if (b == 0) {
throw new IllegalArgumentException("Division by zero");
}
return a / b;
}
public int multiply(int a, int b) {
return a * b;
}
}
Test Class: CalculatorServiceTest
import static org.mockito.Mockito.*;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class CalculatorServiceTest {
@Test
void testStubbingWithException_Divide() {
// Create a mock object of CalculatorService
CalculatorService calculatorService = mock(CalculatorService.class);
// Stub the divide method to throw an exception
when(calculatorService.divide(anyInt(), eq(0))).thenThrow(new IllegalArgumentException("Division by zero"));
// Verify the exception is thrown
IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> {
calculatorService.divide(10, 0);
});
assertEquals("Division by zero", exception.getMessage());
}
@Test
void testStubbingWithException_Multiply() {
// Create a mock object of CalculatorService
CalculatorService calculatorService = mock(CalculatorService.class);
// Stub the multiply method to throw an exception
when(calculatorService.multiply(anyInt(), eq(-1))).thenThrow(new IllegalArgumentException("Negative multiplier"));
// Verify the exception is thrown
IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> {
calculatorService.multiply(10, -1);
});
assertEquals("Negative multiplier", exception.getMessage());
}
}
Explanation
- Creating a Mock:
CalculatorService calculatorService = mock(CalculatorService.class);
This line creates a mock object of the
CalculatorService
class. - Stubbing with Exception for Division:
when(calculatorService.divide(anyInt(), eq(0))).thenThrow(new IllegalArgumentException("Division by zero"));
This line defines the behavior of the
divide
method. When thedivide
method is called with any integer as the first argument and0
as the second argument, it will throw anIllegalArgumentException
. - Using the Mock Object for Division:
IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> { calculatorService.divide(10, 0); });
This line calls the
divide
method on the mock object and checks that the expected exception is thrown. - Asserting the Exception Message for Division:
assertEquals("Division by zero", exception.getMessage());
This line checks if the exception message is as expected.
- Stubbing with Exception for Multiplication:
when(calculatorService.multiply(anyInt(), eq(-1))).thenThrow(new IllegalArgumentException("Negative multiplier"));
This line defines the behavior of the
multiply
method. When themultiply
method is called with any integer as the first argument and-1
as the second argument, it will throw anIllegalArgumentException
. - Using the Mock Object for Multiplication:
IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> { calculatorService.multiply(10, -1); });
This line calls the
multiply
method on the mock object and checks that the expected exception is thrown. - Asserting the Exception Message for Multiplication:
assertEquals("Negative multiplier", exception.getMessage());
This line checks if the exception message is as expected.
Output
Conclusion
Stubbing methods with exceptions using Mockito allows you to simulate error conditions and test how your code handles them. By using thenThrow()
with when()
, you can define stubs that throw exceptions when called, enabling you to test your code’s error handling and robustness. This approach helps ensure that your code can gracefully handle unexpected situations and provides better test coverage for error conditions.