Unit Testing in Java – A Simple, Beginner Friendly Guide
Unit testing is one of the most important skills every Java developer should learn early. It saves time, improves code quality, and is expected in interviews at most modern companies.
What is Unit Testing?
Unit testing means writing small automated tests that verify whether a specific method or function is working correctly. Each test focuses on one “unit” of behavior.
Why Should You Learn Unit Testing?
- You catch bugs early
- You write cleaner and modular code
- You refactor with confidence
- Most product companies expect basic testing knowledge
Tools You Need (JUnit 5)
JUnit 5 is the most commonly used Java testing framework.
For Maven Projects
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.9.1</version>
<scope>test</scope>
</dependency>
Your First Example – Calculator Class
Let’s test a simple Java class.
Calculator.java
public class Calculator {
public int add(int a, int b) { return a + b; }
public int subtract(int a, int b) { return a - b; }
public int multiply(int a, int b) { return a * b; }
public int divide(int a, int b) {
if (b == 0) throw new IllegalArgumentException("Cannot divide by zero");
return a / b;
}
}
CalculatorTest.java (JUnit 5)
import org.junit.jupiter.api.*;
public class CalculatorTest {
private Calculator calculator;
@BeforeEach
void init() {
calculator = new Calculator();
}
@Test
void testAdd() {
Assertions.assertEquals(8, calculator.add(5, 3));
}
@Test
void testSubtract() {
Assertions.assertEquals(6, calculator.subtract(10, 4));
}
@Test
void testMultiply() {
Assertions.assertEquals(10, calculator.multiply(2, 5));
}
@Test
void testDivide() {
Assertions.assertEquals(5, calculator.divide(10, 2));
}
@Test
void testDivideByZero() {
Assertions.assertThrows(IllegalArgumentException.class,
() -> calculator.divide(10, 0));
}
}
How to Run Tests
- Right-click test → Run (IntelliJ/Eclipse)
- Maven: mvn test
- Gradle: gradle test
Best Practices
- Follow Arrange → Act → Assert
- Do not test too many things in one method
- Avoid external systems (DB, APIs)
- Use mocks for dependencies
- Cover edge cases
What to Learn Next
- Mockito (mocking dependencies)
- TDD (Test Driven Development)
- JaCoCo for coverage
- Integration tests
Comments
Post a Comment