Sub topic 1
Why Write Unit Tests?
Every program starts small. You write a method, run it, and look at the output to see if it works. That approach is fine for a while. Then the program grows. You change one method, and something far away breaks without anyone noticing. Unit tests help you catch that kind of problem early. This chapter explains what they are, why they are worth the effort, and where JUnit fits in.
What Is a Unit Test?
A unit is the smallest piece of code you can check on its own. In Java, a unit is usually one method or one small class.
A unit test is a small piece of code that runs a unit and checks that it gives the right result. It answers one question, such as "Does add(2, 3) return 5?"
A good unit test has three traits:
- It is automated. A computer runs it and decides pass or fail. You do not read the output yourself.
- It is fast. It finishes in milliseconds, so you can run hundreds of tests in a few seconds.
- It is isolated. It checks one unit and does not depend on a database, the network, or other tests.
Checking Code by Hand
Most beginners test by hand. They run the program, type some input, and read the answer. This is called manual testing.
Manual testing has real problems:
- It is slow. You repeat the same steps after every change.
- It is easy to forget a case. You might check normal input and skip the edge cases.
- It depends on your attention. If you are tired, you may misread "89" as "90".
- It leaves no record. Next month, nobody remembers which cases you checked.
A Test Without Any Framework
You can write an automated check in plain Java before using any tool. The class below has a method that applies a percentage discount to a price. The main method then checks three cases and prints PASS or FAIL for each.
public class DiscountCheck {
static int applyDiscount(int price, int percent) {
return price - price * percent / 100;
}
public static void main(String[] args) {
check(applyDiscount(100, 10) == 90, "10% off 100 is 90");
check(applyDiscount(50, 0) == 50, "0% off 50 is 50");
check(applyDiscount(80, 100) == 0, "100% off 80 is 0");
}
static void check(boolean ok, String description) {
System.out.println((ok ? "PASS: " : "FAIL: ") + description);
}
}Save it as DiscountCheck.java and run it with Java 11 or newer:
java DiscountCheck.javaThe output is:
PASS: 10% off 100 is 90
PASS: 0% off 50 is 50
PASS: 100% off 80 is 0Now suppose a teammate "simplifies" the method and writes return price - percent; by mistake. Run the same file again and the output changes:
PASS: 10% off 100 is 90
FAIL: 0% off 50 is 50
FAIL: 100% off 80 is 0The first case still passes because 100 minus 10 happens to be 90. The other two cases catch the bug. A bug like this, where code that used to work stops working, is called a regression. Catching regressions is one of the main jobs of unit tests.
Why Unit Tests Are Worth It
Writing tests takes time up front. Here is what you get back.
Bugs Are Found Early and Cheaply
A bug found seconds after you write it is easy to fix, because the code is fresh in your mind. A bug found by a customer weeks later costs much more. Someone has to report it, someone has to find the cause, and the fix has to be shipped again.
You Can Change Code Without Fear
Refactoring means changing how code is written without changing what it does, for example renaming variables or splitting a long method. Without tests, every refactor is a gamble. With tests, you change the code, run the tests, and see right away whether behavior stayed the same.
Tests Explain the Code
A test shows exactly how a method is meant to be used and what it should return. A new team member can read applyDiscount(80, 100) == 0 and learn that a 100% discount makes the price zero. This works like documentation that cannot go out of date, because an outdated test would fail.
Tests Push You Toward Better Design
Code that is hard to test is often badly designed. A method that reads a file, talks to a server, and does math all at once is hard to check. Writing tests nudges you to split code into small parts with clear inputs and outputs.
The Feedback Loop
Unit tests give you a fast feedback loop. You make a change, run the tests, and know within seconds whether you broke something.
Unit Tests Compared with Other Tests
Unit tests are not the only kind of test. Other kinds check larger parts of a system.
| Test type | What it checks | Speed | Example |
|---|---|---|---|
| Unit test | One method or class on its own | Milliseconds | `applyDiscount` returns 90 for 10% off 100 |
| Integration test | Several parts working together | Seconds | The service saves an order to a real database |
| End-to-end test | The whole application, as a user sees it | Seconds to minutes | A browser logs in and places an order |
Most projects have many unit tests, fewer integration tests, and only a few end-to-end tests. Unit tests are the cheapest to write and run, so they form the base.
What Unit Tests Cannot Do
Tests are helpful, but they have limits:
- A test only checks the cases you wrote. Passing tests do not prove the code has no bugs.
- A test with a wrong expected value will happily pass wrong code.
- Unit tests do not check how parts work together. You still need some integration tests.
Why Use a Framework Like JUnit?
The DiscountCheck example works, but it has gaps. It prints results but does not stop the build when a check fails. It does not tell you what value it actually got. It runs checks in one main method, so one crash stops all later checks. There is also no easy way for your IDE or build tool to find and run it.
A testing framework is a library that handles these jobs for you. JUnit is the most widely used testing framework for Java. JUnit 5, also called JUnit Jupiter, is its current major version. JUnit gives you:
- Annotations such as
@Testto mark which methods are tests. - Assertion methods that report the expected and actual values when a check fails.
- A test runner that runs each test separately, so one failure does not hide others.
- Support in every major IDE and in Maven and Gradle, so tests run on every build.
The rest of this tutorial teaches JUnit 5 step by step. The next chapter adds it to a project.
Exercise
In the DiscountCheck example, the buggy version return price - percent; still passed the first check. Why did it pass, and what does this teach you about choosing test cases?
Show answer
For a price of 100 and a percent of 10, both the correct formula (100 - 100 * 10 / 100) and the buggy one (100 - 10) give 90. The bug only shows up with other inputs. You should test several different inputs, including edge cases like 0% and 100%, so that a wrong formula cannot match by luck.
Exercise
Name three traits of a good unit test and explain in one sentence why each one matters.
Show answer
Automated: the computer decides pass or fail, so results do not depend on a person reading output. Fast: tests finish in milliseconds, so you can run them after every change. Isolated: the test checks one unit without a database, network, or other tests, so a failure points straight to the cause.
Exercise
A team says, "All 200 of our unit tests pass, so our app has no bugs." What is wrong with this claim?
Show answer
Passing tests only show that the cases someone wrote behave as expected. There may be inputs nobody tested, tests with wrong expected values, or bugs in how parts work together, which unit tests do not check.