Sub topic 4
Running Tests and Reading the Results
A test helps only when you run it and understand what it tells you. This chapter shows two ways to run JUnit tests: from your IDE and from your build tool. It also shows how to read the results, including the messages you get when a test fails.
The examples use the Calculator class and the CalculatorTest class from the earlier chapters.
Two Ways to Run Tests
There are two common places to run tests.
- An IDE (Integrated Development Environment) is the program where you write code, such as IntelliJ IDEA, Eclipse, or VS Code. It can run one test with a click and show the results in a panel.
- A build tool is a program that compiles and tests your project from the command line. Maven and Gradle are the two most common build tools for Java.
The IDE is faster while you are writing code. The build tool is the official check. Your team and your CI server use the build tool. A CI server is a machine that builds and tests your code each time someone pushes changes.
Running Tests in the IDE
Most IDEs work the same way.
- Open
CalculatorTest. - Find the small green "run" arrow next to the class name or next to a test method.
- Click the arrow next to the class to run all its tests. Click the arrow next to one method to run only that test.
Here is where to find this in each IDE:
| IDE | How to run | Where results appear |
|---|---|---|
| IntelliJ IDEA | Green arrow in the left margin, or right-click and choose "Run 'CalculatorTest'" | Run window with a tree of tests |
| Eclipse | Right-click the file and choose "Run As" then "JUnit Test" | JUnit view with a green or red bar |
| VS Code | Green arrow above the method (needs the Java extensions) | Testing panel in the side bar |
Each test gets an icon. A green check means the test passed. A red mark means it failed. A gray or yellow mark means it was skipped, so it did not run.
Running Tests with Maven
Open a terminal in the project folder, which is the folder that holds pom.xml. Then run:
mvn testMaven compiles your code and your tests, then runs every test. A Maven plugin called Surefire runs the tests. A plugin is an add-on that gives Maven a new job.
You can also run only part of your tests:
# Run one test class
mvn test -Dtest=CalculatorTest
# Run one test method
mvn test -Dtest=CalculatorTest#addReturnsSumWhen all tests pass, the end of the output looks like this:
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESSRunning Tests with Gradle
Open a terminal in the project folder, which is the folder that holds build.gradle.kts. Then run:
./gradlew testOn Windows, use gradlew.bat test. The gradlew file is the Gradle wrapper. It is a small script that downloads the right Gradle version for the project.
To run only part of your tests:
# Run one test class
./gradlew test --tests CalculatorTest
# Run one test method
./gradlew test --tests "CalculatorTest.addReturnsSum"By default, Gradle prints very little when tests pass. You may see only BUILD SUCCESSFUL. To see each test in the console, add testLogging to the test task in build.gradle.kts:
tasks.test {
useJUnitPlatform()
testLogging {
events("passed", "skipped", "failed")
}
}The Four Results a Test Can Have
Each test ends in one of four states. You need to know the difference between them.
| Result | What it means | Typical cause |
|---|---|---|
| Passed | Every assertion was true | The code works as expected |
| Failed | An assertion was false | The code gave a wrong answer, or the test expects the wrong value |
| Error | An unexpected exception was thrown | A bug crashed the code, such as a `NullPointerException` |
| Skipped | The test did not run | The test was turned off on purpose (a later chapter covers this) |
A failure means "the code ran, but the answer was wrong." An error means "the code crashed before it could give an answer." Both stop the build. They point you to different kinds of problems.
Reading a Failure Message
Let's break a test on purpose. Change the assertion in addReturnsSum so it expects the wrong value:
assertEquals(6, result);Run mvn test. The output now includes lines like these:
[ERROR] Tests run: 2, Failures: 1, Errors: 0, Skipped: 0 <<< FAILURE! -- in CalculatorTest
[ERROR] CalculatorTest.addReturnsSum <<< FAILURE!
org.opentest4j.AssertionFailedError: expected: <6> but was: <5>
at CalculatorTest.addReturnsSum(CalculatorTest.java:20)
[ERROR] Failures:
[ERROR] CalculatorTest.addReturnsSum:20 expected: <6> but was: <5>
[ERROR] Tests run: 2, Failures: 1, Errors: 0, Skipped: 0
[INFO] BUILD FAILURERead it piece by piece:
- Which test failed:
CalculatorTest.addReturnsSum. - What kind of problem it was:
AssertionFailedError. This is the exception JUnit throws when an assertion is false, so it is a failure, not an error. - What went wrong:
expected: <6> but was: <5>. The first value is the one you passed as "expected." The second is what the code actually returned. - Where it happened:
CalculatorTest.java:20. This is line 20 of the test file.
The indented at ... lines are the stack trace. A stack trace is the list of method calls that were running when the exception was thrown. Read it from the top. The first line that names one of your own files is usually where you should look.
Put the assertion back to assertEquals(5, result) before you continue.
Reading an Error
Now imagine a bug where the code throws an exception that nobody expected. For example, a test calls calculator.divide(10, 0) without assertThrows. The output then shows:
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0
java.lang.IllegalArgumentException: divisor must not be zero
at Calculator.divide(Calculator.java:9)
at CalculatorTest.divideTest(CalculatorTest.java:30)The count moved to Errors: 1. The top of the stack trace points into Calculator.java, which is the production code. The next line shows which test made the call.
Report Files
Build tools also save the results to files. These files are useful when the console output has scrolled away.
| Build tool | Report location | Format |
|---|---|---|
| Maven | `target/surefire-reports/` | One `.txt` and one `.xml` file per test class |
| Gradle | `build/reports/tests/test/index.html` | A web page you open in a browser |
| Gradle | `build/test-results/test/` | XML files |
CI servers read the XML files to draw charts of passed and failed tests.
Exit Codes
When a command finishes, it returns an exit code. An exit code is a number that tells other programs whether the command worked. 0 means success. Any other number means failure.
mvn test
echo $?If every test passes, echo $? prints 0. If any test fails or has an error, it prints 1. A CI server uses this number to decide whether to accept your change. That is why one failing test turns the whole build red.
Exercises
Exercise
You run mvn test and the summary says "Tests run: 5, Failures: 0, Errors: 1, Skipped: 0". Did an assertion turn out false? Explain.
Show answer
No. Failures is 0, so no assertion was false. Errors is 1, which means one test threw an exception that the test did not expect, such as a NullPointerException. The code crashed before any assertion could fail. Read the top of that test's stack trace to find where.
Exercise
A failure message says "expected: <10> but was: <12>". The test line is assertEquals(10, total). Which value did the code under test return?
Show answer
The code returned 12. In assertEquals the first argument is the expected value (10), and "but was" shows the actual value the code produced (12).
Exercise
You run ./gradlew test twice in a row without editing anything. The second time, no tests seem to run. Why, and how do you force them to run?
Show answer
Gradle sees that nothing has changed since the last run and marks the test task UP-TO-DATE, so it skips it. Run ./gradlew test --rerun, or ./gradlew cleanTest test on Gradle versions older than 7.6.
Exercise
Write the Maven command and the Gradle command that run only the divideByZeroThrows method in CalculatorTest.
Show answer
Maven: mvn test -Dtest=CalculatorTest#divideByZeroThrows. Gradle: ./gradlew test --tests "CalculatorTest.divideByZeroThrows".