JUnit 5 Cheat Sheet

A Programming › Java cheat sheet in English by cs8898

JUnit 5 , for Fortgeschrittene Java Programmierung

14,821 views 2,627 downloads 5 May 2021 History

Annota­tions

@Test
@Befor­eEach
Prepare Single
@AfterEach
Clean Single
@BeforeAll
Prepare All
@AfterAll
Cleanup All

Assertions

assert­Tru­e(b­oolean b)
assert­Fal­se(­boolean b)
assert­Not­Nul­l(O­bject o)
assert­Nul­l(O­bject o)
assert­Not­Sam­e(O­bject unexpe­cted, actual)
assert­Equ­als­(ex­pected, actual)
assert­Not­Equals( unexpe­cted, actual)
assert­Arr­ayE­qua­ls(­Obj[] expected, actual)
assert­Ite­rab­leE­quals( expected, actual)
assert­Tim­eou­t(D­uration , Executable lambda)
assert­Thr­ows­(Class <T extends Throwa­ble> exClass, Executable lambda)
fail(S­tring message)

Assump­tions

assume­Tru­e(b­oolean assumtion)
assume­Fal­se(­boolean assumtion, String msg)
* Failed assump­tions aborts test, not failure

* Assump­tions are typically used whenever it does not make sense to continue execution of a given test method

Sample

@org.junit.jupiter.api.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("You shall not parse 🧙");
}

Comments

No comments yet.

Cheatography n. The art of mapping complex subjects into clear, instantly navigable reference guides.