Mockito
Presented by : Shahrzad Fereidani
Professor : Dr. Ajoudanian
Introduction to Mockito
What is Mockito?
- Mockito is a popular open-source Java mocking framework.
- It allows you to create and configure mock objects for testing purposes.
- Developed to be simple, intuitive, and easy to use.
- Helps in isolating the unit of code being tested by simulating the behavior of
dependencies.
Why Use Mockito?
- Simplifies the creation of mock objects.
- Provides readable and maintainable code for unit tests.
- Eliminates the need for complex setup code.
- Helps achieve high test coverage by isolating and testing individual components.
Key Concepts of Mockito
Mocks:
- Dummy objects that simulate the behavior of real objects.
- Used to isolate the unit of code under test.
- Helps in focusing tests on the behavior of the unit under test, not its dependencies.
Key Concepts of Mockito
Stubbing:
- Configuring mock objects to return specific values when certain methods are called.
- Used to define the behavior of a mock object.
- Helps in testing different scenarios by controlling the return values and exceptions.
Key Concepts of Mockito
Verification:
- Ensuring that certain methods were called on mock objects.
- Used to confirm that the unit of code under test interacted with its dependencies as
expected.
- Helps in validating the correctness of the code logic.
Setting Up Mockito
Add Mockito to your project using Maven or Gradle.
-Example (Maven): org.mockito mockito-core 4.x.x test
- Example (Gradle): testImplementation 'org.mockito:mockito-core:4.x.x
Creating Mocks
- Using @Mock Annotation: @Mock MyService myService;
- Using Mockito.mock(): MyService myService = Mockito.mock(MyService.class);
Practical Example - Testing a Service
Scenario:
- Testing a UserService that depends on a UserRepository.
Code Example:
Advanced Features
Argument Captors:
ArgumentCaptor captor = ArgumentCaptor.forClass(User.class);
verify(userRepository).save(captor.capture());
User capturedUser = captor.getValue();
Spies:
List list = new ArrayList<>();
List spyList = spy(list);
when(spyList.size()).thenReturn(100);
Best Practices
Keep Tests Simple:
- Focus on one behavior per test.
Use Annotations:
- @Mock, @InjectMocks, @Captor for readability.
Avoid Over-Mocking:
- Mock only what you need.
Conclusion
●Mockito is a powerful tool for unit testing in Java.
●It helps create clean, maintainable tests by isolating components.
References and Further Reading
- Mockito Documentation: https://site.mockito.org/ - Books:
- "Mockito Made Clear" by Sujoy Acharya
- "Practical Unit Testing with JUnit and Mockito" by Tomek Kaczanowski
- Online Tutorials: - Baeldung Mockito Guide: https://www.baeldung.com/mockito-series