JUnit 5 Cheatsheet (2023)

junit cheatsheet

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 2024):

<dependencies>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-api</artifactId>
        <version>5.11.0-M2</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-engine</artifactId>
        <version>5.11.0-M2</version>
        <scope>test</scope>
    </dependency>
</dependencies>

Gradle dependencies

Include in your build.gradle the following dependencies:

dependencies {
    testImplementation('org.junit.jupiter:junit-jupiter-api:5.11.0-M2')
    testRuntime('org.junit.jupiter:junit-jupiter-engine:5.11.0-M2')
}

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.