This method is used to create a mock object of a given class or interface. It returns an instance of the specified type with all methods stubbed out.
Mockito is a popular Java library used for unit testing. It allows you to create mock objects to simulate the behavior of real objects and isolate the code you're testing from external dependencies. One of the key features of Mockito is its ability to mock methods, enabling you to define the behavior of mocked methods and verify their interactions.
Here's an explanation and an example of how to use Mockito to mock methods:
1. Creating Mock Objects:
In Mockito, you can create mock objects using the `Mockito.mock()` method. This method generates a mock instance of the specified class or interface. The mock object behaves as if it were a real instance of the class, but you can define its behavior, such as what methods should return or how they should behave when called.
2. Stubbing Method Behavior:
Mocking a method involves defining what it should return when it's called. This is done using the `when().thenReturn()` syntax. You tell Mockito what method to mock and what value to return when that method is called on the mock object.
3. Verifying Method Calls:
After you've defined the behavior of the mock methods and have used them in your code, you can verify if specific methods were called with the expected arguments. This is done using the `verify()` method in Mockito.
Example:
Suppose you have a `Calculator` class that you want to test. This calculator uses an external `MathService` to perform calculations. Here's how you would use Mockito to mock the `MathService` and test the `Calculator`:
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class CalculatorTest {
@Test
public void testAdd() {
// Create a mock MathService
MathService mathService = Mockito.mock(MathService.class);
// Stub the behavior of the add method
when(mathService.add(2, 3)).thenReturn(5);
// Create a Calculator instance using the mock MathService
Calculator calculator = new Calculator(mathService);
// Perform the test
int result = calculator.add(2, 3);
// Verify that the mathService.add method was called with the expected arguments
verify(mathService).add(2, 3);
// Verify the result
assertEquals(5, result);
}
}
In this example, the `MathService` is mocked using `Mockito.mock()`, and its `add` method behavior is defined using `when().thenReturn()`. The test then creates a `Calculator` instance using the mock `MathService`. After performing the calculation, the `verify()` method checks whether the `add` method of the mock was called with the expected arguments.
This example demonstrates how to mock a method's behavior and verify its usage during unit testing using Mockito.