import static java.time.Duration.ofMillis; import static java.time.Duration.ofMinutes; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTimeout; import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; class AssertionsDemo { @Test void standardAssertions() { assertEquals(2, 2); assertEquals(4, 4, "The optional assertion message is now the last parameter."); assertTrue(2 == 2, () -> "Assertion messages can be lazily evaluated -- " + "to avoid constructing complex messages unnecessarily."); } @Test void groupedAssertions() { //分组断言:在一个分组断言中,全部断言都会被执行,而且任何失败的断言也会一块儿被报告 assertAll("address", () -> assertEquals("John", address.getFirstName()), () -> assertEquals("User", address.getLastName()) ); } @Test void exceptionTesting() { Throwable exception = assertThrows(IllegalArgumentException.class, () -> { throw new IllegalArgumentException("a message"); }); assertEquals("a message", exception.getMessage()); } @Test void timeoutNotExceeded() { // 下面的断言成功 assertTimeout(ofMinutes(2), () -> { // 执行任务只需不到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() { // 下面的断言失败,相似的错误信息: // execution exceeded timeout of 10 ms by 91 ms assertTimeout(ofMillis(10), () -> { // 模拟的任务,须要超过10毫秒 Thread.sleep(100); }); } @Test void timeoutExceededWithPreemptiveTermination() { // 下面的断言失败,相似的错误信息: // execution timed out after 10 ms assertTimeoutPreemptively(ofMillis(10), () -> { // 模拟的任务,须要超过10毫秒 Thread.sleep(100); }); } private static String greeting() { return "hello world!"; } }
import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import org.junit.jupiter.api.Test; class HamcrestAssertionDemo { @Test void assertWithHamcrestMatcher() { assertThat(2 + 1, is(equalTo(3))); } }
附录:参考java