How to use Mockito for Unit Testing in Java Application

Опубликовано: 18 Январь 2026
на канале: raksrahul
144
3

How to use Mockito for Unit Testing in Java Application

1. Create a simple Maven project.

2. For testing with mockito two dependencies are required :

a. Mockito - Provides annotations for mocking objects
b. Junit - Java junit framework

3. Import these dependencies by copying in pom.xml and build the project.

4. Let us create unit tests for UserService.

5. Name the class as UserServiceTest in src/test/java folder.
UserService is dependent on UserDao but we only want to test UserService class and not actually call UserDao.
Hence, we will mock the UserDao class via @Mock annotation.
The instance of class we want to test will be annotated by @InjectMocks annatation.
Annotate the UserServiceTest class with @RunWith(MockitoJUnitRunner.class) annotations.

6. Write the test methods.

7. Run Junit tests.

8. Finish.

#java #mockito #unittesting #junit #mockitoframework