Sub topic 3
Your First JUnit Test
In this chapter you will write a real test, see it pass, and then break it on purpose to see it fail. You will also learn the rules JUnit uses to find and run your tests. These rules explain many of the "why didn't my test run?" problems that beginners run into.
The Code We Want to Test
You need some code before you can test it. The code you test is called the code under test. Here it is a small class named Calculator.
Save this file as src/main/java/Calculator.java:
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public int divide(int a, int b) {
if (b == 0) {
throw new IllegalArgumentException("divisor must not be zero");
}
return a / b;
}
}For now we will only test add. A later chapter tests divide, including the case where it throws an exception.
Where Test Code Lives
Maven and Gradle keep your code in two separate folders:
| Folder | What goes there | Part of the final app? |
|---|---|---|
| `src/main/java` | Production code, the code your users run | Yes |
| `src/test/java` | Test code, the code that checks the production code | No |
Production code is the real program you ship. Test code exists only to check it. The build tool puts JUnit on the classpath for src/test/java only. The classpath is the list of places Java looks for classes. If you put a test in src/main/java by mistake, the compiler cannot find JUnit and the build fails.
Writing the Test Class
A test class is an ordinary Java class that holds tests. By convention, its name is the class under test plus Test, so ours is CalculatorTest.
A test method is a method that checks one piece of behavior. You mark it with the @Test annotation. An annotation is a label that starts with @. It gives tools extra information about your code. @Test tells JUnit "run this method as a test."
Save this as src/test/java/CalculatorTest.java:
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class CalculatorTest {
@Test
void addReturnsSumOfTwoPositiveNumbers() {
Calculator calculator = new Calculator();
int result = calculator.add(2, 3);
assertEquals(5, result);
}
@Test
void addWorksWithNegativeNumbers() {
Calculator calculator = new Calculator();
int result = calculator.add(-4, 1);
assertEquals(-3, result);
}
}Let's go through it line by line.
import static org.junit.jupiter.api.Assertions.assertEquals;is a static import. It lets you writeassertEquals(...)instead ofAssertions.assertEquals(...).import org.junit.jupiter.api.Test;brings in the@Testannotation. Note the package:org.junit.jupiter.api. That is JUnit 5.class CalculatorTesthas nopublickeyword. JUnit 5 does not need it.@Testsits above each method that JUnit should run.- Each method creates a
Calculator, callsadd, and checks the answer.
What assertEquals Does
An assertion is a check that stops the test if something is wrong. assertEquals(expected, actual) compares two values:
- If they are equal, nothing happens and the method keeps going.
- If they differ, JUnit throws an
AssertionFailedErrorand marks the test as failed.
The order matters for the message. Put the value you expect first and the value you got second. If you swap them, the failure message will read backwards and confuse you. The assertions chapter covers many more assertions. For now, assertEquals is all you need.
Pass, Fail, and Error
Every test ends in one of these states:
| Result | What happened | Example |
|---|---|---|
| Passed | The method finished with no exception | `assertEquals(5, 5)` |
| Failed | An assertion was not met | `assertEquals(6, 5)` |
| Error / aborted | Some other exception was thrown, or the test could not start | A `NullPointerException` inside the test |
A test with no assertions at all passes as long as it throws nothing. That is a trap: such a test checks almost nothing. Make sure every test asserts something.
Seeing a Test Fail on Purpose
A test you have never seen fail might not be checking what you think. So break it once. Change the first test's expected value from 5 to 6:
@Test
void addReturnsSumOfTwoPositiveNumbers() {
Calculator calculator = new Calculator();
int result = calculator.add(2, 3);
assertEquals(6, result);
}Run the tests. In the IDE, click the green arrow next to the class name. From the command line, run mvn test or gradle test. The next chapter covers running tests in detail. You will see a message like this:
org.opentest4j.AssertionFailedError: expected: <6> but was: <5>The message gives the value you expected (6) and the value the code actually returned (5). Here the test was wrong, not the code, so change 6 back to 5. When a real test fails, this message is your first clue about what broke.
How JUnit Finds and Runs Your Tests
You never write a main method for tests. JUnit does the work for you. It scans your test classes, finds every method marked @Test, and runs each one.
Look at the step "Create a NEW instance." JUnit makes a fresh object of your test class for every test method. So one test cannot change a field and affect another test. This demo proves it:
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class FreshInstanceTest {
private int counter = 0;
@Test
void firstTest() {
counter++;
assertEquals(1, counter);
}
@Test
void secondTest() {
counter++;
assertEquals(1, counter);
}
}Both tests pass. Each one starts with counter at 0, because each runs on its own new object. JUnit also does not promise any order for test methods, so never write a test that depends on another test running first.
Rules for a Test Method
JUnit only runs a method if it follows a few rules. Break one and the test may be skipped without any clear warning. That is the hardest kind of bug to spot.
| Rule | Correct | What goes wrong otherwise |
|---|---|---|
| Must have `@Test` from `org.junit.jupiter.api` | `import org.junit.jupiter.api.Test;` | `org.junit.Test` is JUnit 4, and JUnit 5 ignores it |
| Must not be `private` | `void addWorks()` | A private method is not run |
| Must not be `static` | `void addWorks()` | A static method is not run |
| Must return `void` | `void addWorks()` | `int addWorks()` is not run |
| Should take no parameters (for now) | `void addWorks()` | JUnit cannot supply the values and reports an error |
Methods with parameters do have a use. Later chapters show how JUnit can fill them in, for example in parameterized tests. Until then, keep your test methods without parameters.
Edge Cases Worth Knowing
- Helper methods without
@Testare fine. You can add a private method likeprivate Calculator newCalculator()to the test class. JUnit will not run it as a test, but your tests can call it. - One class can hold many tests. Add as many
@Testmethods as you need. Each runs on its own. - The test class needs a usable constructor. Leave it with the default no-argument constructor. If you add a constructor that takes arguments, JUnit cannot build the class.
- Abstract classes are not run directly. JUnit cannot create an instance of an abstract class, so its tests run only through a concrete subclass.
Exercise
Write a test method in CalculatorTest that checks that add(0, 0) returns 0. Include the annotation and follow all the method rules.
Show answer
@Test void addOfZerosIsZero() { Calculator calculator = new Calculator(); int result = calculator.add(0, 0); assertEquals(0, result); } It uses @Test from org.junit.jupiter.api, is not private or static, returns void, and takes no parameters.
Exercise
A teammate writes "private void addWorks()" with @Test above it. The build passes and the report is green. Is the add method tested? Why or why not?
Show answer
No. JUnit does not run private test methods, so the method was never called. The green report only means no test failed. Remove "private" so the method runs.
Exercise
You run a test and see "expected: <10> but was: <12>". Which value came from your code, and which one did you write in the test?
Show answer
12 came from the code under test (the actual value). 10 is the expected value you wrote as the first argument to assertEquals.