Mockito.when() is a fundamental method used in Mockito, a popular mocking framework for Java unit tests. It’s primarily utilized for stubbing, which means pre-defining the behavior of a mock object for specific method calls. Here’s an overview of its usage and importance in unit testing.
Syntax and Components
- mockObject: The mock instance of a class created using Mockito.
- methodCall(parameters): The method of the mock object for which behavior is defined.
- returnValue: The value that the method will return when called with specified parameters.
Consider a service
MyService with a method
getData(). To create a mock of
MyService that returns specific data when
getData() is called, you would use:
// Creating a mock object of MyService
MyService mockService = Mockito.mock(MyService.class);
// Defining the behavior of mockService.getData()
- Argument Matchers: Use matchers like
eq(), etc., for a range of argument values.
- Throwing Exceptions: Make the mock throw an exception using
- Multiple Calls: Define different behaviors for subsequent calls to the same method.
Mockito.when()only with mock objects, not with real instances.
- It’s part of the given-when-then pattern in testing, used in the ‘Arrange’ or ‘Given’ phase.
- For void methods, use
Mockito.when() is essential for Java developers writing unit tests, as it helps create predictable and isolated test scenarios.