Java Reference ยท Language Features by Version
Testing Java with JUnit
Reference for JUnit Jupiter: @Test, assertions, assertThrows, lifecycle annotations, parameterized tests, @Nested and how to run tests from Maven or code.
JUnit is the standard framework for automated tests in Java. A test is a method that calls your code and asserts that the result is right; a build tool or IDE runs all tests and reports which failed. This page is a quick reference for JUnit Jupiter, the programming model of JUnit 5 and 6 (current: 6.1), with runnable examples. For a guided walk-through read the lessons linked at the end.
JUnit is made of three parts: the Platform (the launcher that discovers and runs tests), Jupiter (the annotations and assertions you write with, in org.junit.jupiter.api) and optional engines for other frameworks. JUnit 6 requires Java 17 or newer.
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; class PriceTest { @Test void addsTax() { assertEquals(120, Price.withTax(100, 20)); } }
In a real project you do not launch tests by hand: mvn test, gradle test or your IDE find classes with @Test methods. The runnable examples below start the JUnit Platform launcher from main, which is only there so a test class can run in this sandbox. Each shows its results sorted by name so the output is stable.
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Core annotations
| Annotation | Meaning |
|---|---|
@Test |
Marks a test method (no parameters, returns void, not private or static) |
@DisplayName("...") |
Readable name for reports |
@BeforeEach, @AfterEach |
Run around every test; the test class is created anew per test |
@BeforeAll, @AfterAll |
Run once per class; methods must be static unless @TestInstance(PER_CLASS) |
@Disabled("reason") |
Skip a test or class |
@Nested |
Group tests in an inner (non-static) class |
@ParameterizedTest |
Run one method with many inputs: @ValueSource, @CsvSource, @MethodSource, @EnumSource |
@RepeatedTest(n) |
Repeat a test |
@Timeout(2) |
Fail if the test runs longer than 2 seconds |
@TempDir |
Inject a temporary directory deleted after the test |
@Tag("slow") |
Label tests so builds can include or exclude groups |
Common assertions
All are static methods of Assertions. The expected value comes first, then the actual value, then an optional message (or a message supplier).
| Method | Checks |
|---|---|
assertEquals(expected, actual) |
Equality with equals; for double add a delta: assertEquals(0.3, x, 1e-9) |
assertSame, assertNotSame |
Identity (==) |
assertTrue, assertFalse, assertNull, assertNotNull |
Conditions |
assertThrows(Type.class, executable) |
The code throws that type (or a subtype) and returns the exception for inspection |
assertDoesNotThrow(executable) |
No exception |
assertAll(...) |
Runs every check and reports all failures together |
assertIterableEquals, assertArrayEquals, assertLinesMatch |
Collections, arrays and text |
assertTimeout(duration, executable) |
Time limit |
fail("message") |
Fail unconditionally |
Usage notes
- Name tests after behavior, such as
rejectsNegativeQuantity, nottest1. A failing name should say what broke. - Arrange, act, assert. One logical behavior per test; keep tests independent and free of order assumptions.
- Do not test the framework or trivial getters. Spend effort on logic with branches, boundaries and error handling.
- Use
assertThrows, not try/catch withfail. It is shorter and also fails if no exception is thrown. - Mock only the edges (network, clock, filesystem). Libraries such as Mockito replace collaborators; prefer small fakes you write yourself when they are simple.
- Floating-point values need a tolerance.
assertEquals(0.1 + 0.2, 0.3)fails. - JUnit 4 differences. JUnit 4 uses
org.junit.Test,@Before,@After,@RunWith. Jupiter uses different packages and annotations; the Vintage engine runs old tests during a migration. - Run from the command line with the Maven Surefire plugin (
mvn test), Gradle (gradle testwithuseJUnitPlatform()), or the standalone console launcher JAR. Use-Dtest=ClassName#methodin Maven to run one test. - Assertion libraries such as AssertJ and Hamcrest give more readable checks and better failure messages; they work with JUnit but are separate dependencies.
Related
- Maven and Gradle
- Assertions in the language: assert
- Logging
- Tutorial: Unit Testing
- Tutorial: Unit Testing with JUnit 6