Unit testing is a software testing technique used to verify that individual components of an application, such as methods, classes, or functions, work correctly in isolation. The primary goal is to detect defects early in the development process and ensure that each unit behaves as expected.
Why Is Unit Testing Important?
During development, changes are made frequently.
What Does a Unit Test Verify?
Suppose we have a method that calculates the total price of products.
calculateTotal(100, 20)
120
A unit test verifies that the method consistently returns the correct result.
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class Calculator {
public int add(int a, int b) {
return a + b;
}
}
public class CalculatorTest {
@Test
void testAddition() {
Calculator calculator =
new Calculator();
assertEquals(
10,
calculator.add(5, 5));
}
}Benefits of Unit Testing
1. Early Bug Detection
Issues are identified during development instead of production.
2. Safer Refactoring
Developers can modify code with confidence because tests verify existing functionality.
3. Better Code Quality
Writing testable code often leads to cleaner design and better separation of concerns.
4. Faster Development Cycles
Automated tests reduce manual verification efforts.
5. Documentation of Behavior
Tests clearly describe how the code is expected to work.
Common Tools for Unit Testing in Java
Mockito is often used to mock dependencies so that only the target unit is tested.
A service depends on a database repository.
This keeps tests fast and isolated.
Real-World Example
Consider an online banking application.
A method transfers money between accounts.
This ensures the business logic works correctly before deployment.
Unit Testing vs Integration Testing
A concise interview answer is
Unit testing is the practice of testing individual units of code, such as methods or classes, in isolation to ensure they work correctly. It helps detect defects early, improves code quality, supports safe refactoring, and increases application reliability. In Java, unit testing is commonly performed using frameworks like JUnit and Mockito.
Last updated: 16 July 2026
Previous question: How do you test a Spring Boot application?
Next question: How do JUnit and Mockito facilitate unit testing in Java projects?