JUnit and Mockito are two widely used testing frameworks in Java that help developers write effective unit tests. JUnit provides the structure and assertions needed to create and execute test cases, while Mockito helps isolate the code being tested by creating mock objects for external dependencies. Together, they enable fast, reliable, and maintainable unit testing.
What is the Role of JUnit?
JUnit is the foundation of unit testing in Java.
import static org.junit.jupiter.api.Assertions.*;
@Test
void testAddition() {
assertEquals(10, 5 + 5);
}If the expected and actual values match, the test passes.
What is the Role of Mockito?
Mockito helps create mock objects for dependencies that are not part of the unit being tested.
Instead of calling real systems, Mockito creates fake objects with predefined behavior.
EmployeeRepository repository =
Mockito.mock(EmployeeRepository.class);when(repository.findById(1L))
.thenReturn(
new Employee(
1L,
"John"));This allows testing without connecting to a real database.
Why Use JUnit and Mockito Together?
EmployeeService
|
EmployeeRepository
|
Database
Mockito replaces the repository with a mock object.
JUnit executes and validates the test.
@Service
public class EmployeeService {
private EmployeeRepository repository;
public EmployeeService(
EmployeeRepository repository) {
this.repository = repository;
}
public Employee getEmployee(Long id) {
return repository.findById(id)
.orElse(null);
}
}@ExtendWith(MockitoExtension.class)
class EmployeeServiceTest {
@Mock
private EmployeeRepository repository;
@InjectMocks
private EmployeeService service;
@Test
void shouldReturnEmployee() {
Employee employee =
new Employee(
1L,
"John");
when(repository.findById(1L))
.thenReturn(
Optional.of(employee));
Employee result =
service.getEmployee(1L);
assertEquals(
"John",
result.getName());
}
}Benefits of JUnit
Benefits of Mockito
This makes tests faster and more predictable.
Real-World Example
This allows developers to test business logic without accessing real banking systems.
A concise interview answer is
JUnit provides the framework for writing and executing unit tests, while Mockito helps create mock objects for external dependencies. Together, they allow developers to test a class in isolation, making unit tests faster, more reliable, and independent of databases, APIs, or other external systems.
Last updated: 11 November 2026
Previous question: What is the purpose of unit testing in software development?
Next question: What is the difference between @Mock and @InjectMocks in Mockito?