Unit testing is a way to test small parts of your code.
We test one “unit” at a time, like one method or class.
JUnit is a tool to help you write and run these tests in Java.
Imagine you bake a cake.
Before giving it to someone, you taste a small piece.
You check if it is good or has problems.
Unit testing is the same idea for software.
We check parts of our program to make sure they work.
JUnit is a testing framework for Java.
It lets you write code to test your other code.
It tells you if your code works or breaks.
junit
to your project (use Maven or Gradle or add the JAR).@Test
annotation.Let’s say we have a class to add two numbers:
public class Calculator {
public int add(int a, int b) {
return a + b;
}
}
Now we write a test for it using JUnit:
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class CalculatorTest {
@Test
public void testAdd() {
Calculator calc = new Calculator();
int result = calc.add(2, 3);
assertEquals(5, result);
}
}
Here:
@Test
tells JUnit this is a test method.assertEquals
checks if the result is what we expect.Imagine a method that returns the bigger of two numbers:
public class MathUtils {
public int max(int a, int b) {
return a > b ? a : b;
}
}
Test it like this:
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class MathUtilsTest {
@Test
public void testMax() {
MathUtils mu = new MathUtils();
assertEquals(8, mu.max(5, 8));
assertEquals(10, mu.max(10, 3));
}
}
Let’s say you are writing an app for a bakery.
You have a method that gives a discount if someone buys more than 5 cupcakes.
public class Bakery {
public double getPrice(int count) {
double price = count * 2.0;
if (count > 5) {
price *= 0.9; // 10% discount
}
return price;
}
}
Now test it:
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class BakeryTest {
@Test
public void testGetPrice() {
Bakery b = new Bakery();
assertEquals(10.0, b.getPrice(5));
assertEquals(10.8, b.getPrice(6), 0.001);
}
}
We use 0.001
for floating point accuracy.
JUnit will show a red bar or error message.
It tells you what failed and where.
This helps you fix your code faster.
Testing is part of good software engineering.
JUnit makes testing easy in Java.
Write small tests. Run them often. Fix bugs quickly.
Happy testing!