🎯Mockito
Introduction
Mockito is an open-source Java testing framework that allows developers to create mock objects of classes and interfaces to test the behavior of other objects in the system. It is widely used to mock dependencies in unit tests, allowing developers to test individual units of code in isolation.
Basic Syntax
Creating a mock object:
Setting expectations on mock objects:
Verifying the behavior of mock objects:
Mocking Methods
Returning a specific value:
Throwing an exception:
Calling the real method:
Verifying Behavior
Verifying that a method was called:
Verifying that a method was not called:
Verifying that a method was called with specific arguments:
Advanced Features
Mocking void methods:
Mocking static methods:
Mocking final methods:
Matchers
Matchers allow developers to specify more complex argument matching for method calls on mock objects.
Using argument matchers:
Combining matchers:
Annotations
@Mock: Declares a mock object to be created and injected.
@InjectMocks: Injects the mocked dependencies into the class being tested.
@RunWith(MockitoJUnitRunner.class): Runs the tests using the Mockito test runner.
Last updated