JUnit 5 Cheatsheet (2023)
Staying productive with JUnit 5 Jupiter requires a quick reference for common annotations, assertions, lifecycle hooks, and conditional execution rules. This updated JUnit 5 Cheatsheet provides a concise overview of modern testing patterns for Java 17/21 applications. Use this guide to quickly look up Maven/Gradle dependencies, assertions, assumptions, and conditional annotations.
This article contains a JUnit 5 Cheatsheet which you can use as handy reference to build your JUnit 5 Jupiter Tests in Java.
Maven Dependencies:
Here is the list of dependencies you have to include in your pom.xml according to the latest JUnit version (May 2026):
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>6.1.0-RC1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>6.1.0-RC1</version>
<scope>test</scope>
</dependency>
</dependencies>
Gradle dependencies
Include in your build.gradle the following dependencies:
dependencies {
testImplementation('org.junit.jupiter:junit-jupiter-api:6.1.0-RC1')
testRuntime('org.junit.jupiter:junit-jupiter-engine:6.1.0-RC1')
}
Basic JUnit 5Test
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class JUnit5ExampleTest {
@Test
void firstTest() {
assertEquals("ok","ok");
}
}
Lifecycle:
Callback methods that will run according to Test lifecycle:
import org.junit.jupiter.api.*;
public class AppTest {
@BeforeAll
static void setup(){
System.out.println("Executes a method Before all tests");
}
@BeforeEach
void setupThis(){
System.out.println("Executed Before each @Test method in the current test class");
}
@AfterEach
void tearThis(){
System.out.println("Executed After each @Test method in the current test class");
}
@AfterAll
static void tear(){
System.out.println("Executes a method After all tests");
}
}
Assertions
Assertions help in validating the expected output with the actual output of a test.
@Test
void exampleTest() {
Assertions.assertTrue(trueBool);
Assertions.assertFalse(falseBool);
Assertions.assertNotNull(notNullString);
Assertions.assertNull(notNullString);
Assertions.assertNotSame(originalObject, otherObject);
Assertions.assertEquals(4, 4);
Assertions.assertNotEquals(3, 2);
Assertions.assertArrayEquals(new int[]{1,2,3}, new int[]{1,2,3}, "Array Equal Test");
Iterable<Integer> listOne = new ArrayList<>(Arrays.asList(1,2,3,4));
Iterable<Integer> listTwo = new ArrayList<>(Arrays.asList(1,2,3,4));
Assertions.assertIterableEquals(listOne, listTwo);
Assertions.assertTimeout(Duration.ofMillis(100), () -> {
Thread.sleep(50);
return "result";
});
Throwable exception = Assertions.assertThrows(IllegalArgumentException.class, () -> {
throw new IllegalArgumentException("error message");
});
Assertions.fail("not found good reason to pass");
}
Assumptions
A failed assumption results in a test being aborted because it does not make sense to continue execution of a given test method.
@Test
void testAssumption() {
System.setProperty("myproperty", "foo");
Assumptions.assumeTrue("foo".equals(System.getProperty("myproperty")));
}
@Test
public void testConnection() {
boolean isConnected = checkConnection(); // Some method that checks the network connection
assumingThat(isConnected, () -> {
// Test code that requires an active network connection
// e.g. test to check the API call
assertTrue(myApiCall().contains("Hello World"));
});
}
Conditional Execution
Your Test will be executed according to a set of different conditions available in org.junit.jupiter.api.condition package.
JRE Conditional Execution
Conditional execution based on JRE that you are using to start the Test.
public class AppTest
{
@Test
@EnabledForJreRange(min = JRE.JAVA_8, max = JRE.JAVA_11)
public void test1()
{
System.out.println("Will run only on JRE between 8 and 11");
}
@Test
@EnabledOnJre({JRE.JAVA_8, JRE.JAVA_11})
public void test2()
{
System.out.println("Will run only on JRE 8 and 11");
}
@Test
@DisabledForJreRange(min = JRE.JAVA_8, max = JRE.JAVA_11)
public void test3()
{
System.out.println("Will NOT run on JRE between 8 and 11");
}
@Test
@DisabledOnJre({JRE.JAVA_8, JRE.JAVA_11})
public void test4()
{
System.out.println("Will NOT run on JRE 8 and 11");
}
}
Operating System Conditional Execution
public class OperatingSystemTest {
@Test
@EnabledOnOs({OS.LINUX, OS.WINDOWS})
void onLinuxOrWindows() {
System.out.println("Will run on Linux or Windows.");
}
@Test
@DisabledOnOs({OS.WINDOWS, OS.AIX, OS.SOLARIS, OS.MAC})
void notOnWindowsOrAixOrSolarisOrMac() {
System.out.println("Will not run on Windows, AIX, Solaris or MAC!");
}
}
Method return value Conditional Execution
@Test
@EnabledIf("myfunction")
void enabled() {
assertTrue(true);
}
@Test
@DisabledIf("myfunction")
void disabled() {
assertTrue(true);
}
boolean myfunction() {
return true;
}
Env variable and System Property Conditional Execution
@Test
@EnabledIfEnvironmentVariable(named = "ENV", matches = ".*oracle.*")
public void executeOnlyInDevEnvironment() {
return true;
}
@Test
@DisabledIfEnvironmentVariable(named = "ENV", matches = ".*mysql.*")
public void disabledOnProdEnvironment() {
return true;
}
@Test
@EnabledIfSystemProperty(named = "my.property", matches = "prod*")
public void onlyIfMyPropertyStartsWithProd() {
return true;
}
Repeated jUnit Tests
The @RepeatedTest annotation enable to run multiple times single tests in JUnit 5. The number of times the test will be executed can be configured as parameter to @RepeatedTest annotation.
@Test
@RepeatedTest(5)
void addNumber() {
Calculator calculator = new Calculator();
Random rand = new Random();
int n = rand.nextInt(50);
Assertions.assertEquals(n*2, calculator.add(n, n), "Checking calculator sum");
}
Testsuite
Using JUnit 5 test suites, you can run tests spread into multiple test classes and different packages:
@RunWith(JUnitPlatform.class)
@SelectPackages("com.howtodoinjava.junit5.examples.packageA")
public class JUnit5TestSuiteExample
{
}
Conclusion
JUnit 5 cheatsheet was provided by Mastertheboss.com. Check the list of our CheatSheets.
Frequently Asked Questions
Which Maven dependency is required for JUnit 5 Jupiter?
Add org.junit.jupiter:junit-jupiter (version 5.10+ / 5.12+) to your pom.xml test scope, which aggregates API, params, and engine dependencies into a single declaration.
How do I disable a JUnit 5 test conditionally?
Use annotations from org.junit.jupiter.api.condition like @EnabledOnOs(OS.LINUX), @EnabledOnJre(JRE.JAVA_21), or @DisabledIfSystemProperty.
Recommended Articles
Maximize Test Efficiency with JUnit AssertTimeout: A Comprehensive Guide
Learn how to implement timeout assertions in JUnit tests to ensure timely test execution and prevent lengthy tests from running indefinitely.
Master JUnit Assertions for Robust Java Unit Testing
Learn how to use JUnit assertions for robust unit testing in Java, including assertAll, assertEquals, and more.
Unlock JUnit 5 Test Execution in Maven Projects - A Comprehensive Guide
Ensure your JUnit 5 tests run smoothly with this comprehensive guide to resolving common issues.
How to Assert No Exception Thrown in Java with JUnit 4 and JUnit 5
Learn how to assert no exception thrown in Java tests using JUnit 4 and JUnit 5. #Java #JUnit #Testing #CloudNative