Unit Testing in Java - Explained Simply
1. Start with a Simple Example
Imagine you wrote a Java method to calculate the square of a number. Before using it in a big project, you
want to check if it's giving the correct results. That's what unit testing does - testing individual methods or
functions in your Java code to ensure they work correctly.
2. Simple Definition
Unit Testing in Java means testing one unit of code - usually a method - to check if it works as expected. We
write a test class using a tool called JUnit.
3. Why is Unit Testing Useful?
- Catches bugs early
- Makes code easy to change safely
- Improves code quality
- Speeds up development
- Helps in Test Driven Development (TDD)
4. Where Does It Fit?
Unit testing is the first level of testing, where we test one class or method. After that comes integration
testing, system testing, and user acceptance testing.
5. Java Code Example
public class Calculator {
public static int add(int a, int b) {
return a + b;
Page 1
Unit Testing in Java - Explained Simply
6. Unit Test Using JUnit
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class CalculatorTest {
@Test
public void testAdd() {
int result = Calculator.add(2, 3);
assertEquals(5, result);
7. What is JUnit?
JUnit is a Java framework that helps us write unit tests. It has annotations like @Test and methods like
assertEquals(expected, actual).
8. Basic JUnit Annotations
@Test - Marks a method as a test case
@Before - Runs before each test
@After - Runs after each test
@BeforeClass - Runs once before all tests
@AfterClass - Runs once after all tests
Page 2
Unit Testing in Java - Explained Simply
9. Assertions in JUnit
assertEquals(a,b) - Checks if a == b
assertTrue(cond) - Checks if condition is true
assertNotNull(x) - Checks if x is not null
assertFalse(cond) - Checks if condition is false
10. How to Run Unit Tests
- Use IntelliJ or Eclipse -> Right-click -> Run
- Maven: mvn test
- Gradle: ./gradlew test
11. Best Practices
- Name test classes like ClassNameTest
- Write one test per method
- Use clear naming
- Avoid database or network calls in unit tests
- Run tests often
12. Final Wrap-Up
Unit testing in Java means writing separate test classes that check if your methods are working right. We use
JUnit for that. For example, if you have an add() method, we write a test to check if add(2, 3) gives 5. If it
does, the test passes. It helps us catch bugs early and keeps our code strong.
Page 3