Different Methods from Mockito Framework
Mockito is a powerful tool for creating mock objects and defining their behavior. Here are some of the most commonly used methods in Mockito, along with their sequence of usage:
1. mock()
Creates a mock instance of a class or interface.
MyClass mockObject = mock(MyClass.class);
2. when(...).thenReturn(...)
Defines the behavior of the mock when a method is called.
when(mockObject.someMethod()).thenReturn("Mocked Response");
3. verify(...)
Verifies that a method was called on the mock object with specific parameters.
verify(mockObject).someMethod();
4. verifyNoMoreInteractions(...)
Checks that no other interactions have occurred on the mock object.
verifyNoMoreInteractions(mockObject);
5. reset(...)
Resets the mock object to its initial state.
reset(mockObject);
Sequence of Usage
Here's a typical sequence of using Mockito methods in a test:
-
mock()
- Create mock objects. -
when(...).thenReturn(...)
- Define behavior for the mock objects. Execute the code under test. -
verify(...)
- Verify interactions with the mock objects. -
verifyNoMoreInteractions(...)
- Ensure no unexpected interactions. -
reset(...)
- Optional: Reset mocks for reuse in other tests.
Example
import static org.mockito.Mockito.*;
public class ExampleTest {
@Test
public void testExample() {
// 1. Create mock
MyClass mockObject = mock(MyClass.class);
// 2. Define behavior
when(mockObject.someMethod()).thenReturn("Mocked Response");
// Code under test
String result = mockObject.someMethod();
// 3. Verify interactions
verify(mockObject).someMethod();
// Optional: Verify no more interactions
verifyNoMoreInteractions(mockObject);
// Optional: Reset mock
reset(mockObject);
}
}
Conclusion
Mockito provides a set of methods to create, configure, and verify mock objects in unit tests. The sequence of creating a mock, defining its behavior, executing tests, and verifying interactions ensures that unit tests are isolated and reliable.
Top comments (0)