1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
| import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test;
import static java.time.Duration.ofMillis; import static java.time.Duration.ofMinutes; import static org.junit.jupiter.api.Assertions.*;
class AssertionsDemo {
private static Person person;
@BeforeAll public static void beforeAll() { person = new Person("John", "Doe"); }
@Test void standardAssertions() { assertEquals(2, 2); assertEquals(4, 4, "The optional assertion message is now the last parameter."); assertTrue('a' < 'b', () -> "Assertion messages can be lazily evaluated -- " + "to avoid constructing complex messages unnecessarily."); }
@Test void groupedAssertions() { assertAll("person", () -> assertEquals("John", person.getFirstName()), () -> assertEquals("Doe", person.getLastName())); }
@Test void dependentAssertions() { assertAll("properties", () -> { String firstName = person.getFirstName(); assertNotNull(firstName);
assertAll("first name", () -> assertTrue(firstName.startsWith("J")), () -> assertTrue(firstName.endsWith("n"))); }, () -> { String lastName = person.getLastName(); assertNotNull(lastName);
assertAll("last name", () -> assertTrue(lastName.startsWith("D")), () -> assertTrue(lastName.endsWith("e"))); }); }
@Test void exceptionTesting() { Throwable exception = assertThrows(IllegalArgumentException.class, () -> { throw new IllegalArgumentException("a message"); }); assertEquals("a message", exception.getMessage()); }
@Test void timeoutNotExceeded() { assertTimeout(ofMinutes(2), () -> { }); }
@Test void timeoutNotExceededWithResult() { String actualResult = assertTimeout(ofMinutes(2), () -> { return "a result"; }); assertEquals("a result", actualResult); }
@Test void timeoutNotExceededWithMethod() { String actualGreeting = assertTimeout(ofMinutes(2), AssertionsDemo::greeting); assertEquals("Hello, World!", actualGreeting); }
@Test void timeoutExceeded() { assertTimeout(ofMillis(10), () -> { Thread.sleep(100); }); }
@Test void timeoutExceededWithPreemptiveTermination() { assertTimeoutPreemptively(ofMillis(10), () -> { Thread.sleep(100); }); }
private static String greeting() { return "Hello, World!"; }
}
|