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