org.junit.Assert → org.junit.jupiter.api.Assertionsorg.junit.Test → org.junit.jupiter.api.Testorg.junit.jupiter.*import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class Test1 {
@Test
public void test() {
Assertions.assertEquals(3 * 6, 18);
Assertions.assertTrue(5 > 4);
}
}
@Test
public void lambdaExpressions() {
// 條件用 Lambda,失敗時才計算訊息
Assertions.assertTrue(() -> "".isEmpty(), "string should be empty");
// 訊息用 Lambda,延遲評估
Assertions.assertEquals("foo", "foo", () -> "message is lazily evaluated");
}
避免不必要的字串建構開銷,特別是複雜失敗訊息。
JUnit 4 單測建議單一斷言,JUnit 5 assertAll 允許一組斷言全部執行並彙總報告所有失敗:
@Test
public void groupedAssertions() {
Dimension dim = new Dimension(800, 600);
Assertions.assertAll("dimension",
() -> Assertions.assertEquals(800, dim.width, "width"),
() -> Assertions.assertEquals(600, dim.height, "height")
);
}
// 輸出:Multiple Failures (2 failures)
// dimension: width expected:<800> but was:<...>
// dimension: height expected:<600> but was:<...>
不再使用 @Test(expected=...) 或 try-catch,改用功能風格:
@Test
public void exceptions() {
// 僅斷言型別
Assertions.assertThrows(RuntimeException.class, () -> {
throw new NullPointerException();
});
// 斷言並取得異常物件進行深度驗證
Throwable ex = Assertions.assertThrows(RuntimeException.class, () -> {
throw new NullPointerException("should not be null");
});
Assertions.assertEquals("should not be null", ex.getMessage());
}
public class Test3 {
@Test @Disabled // 替代 JUnit 4 @Ignore
public void disabledTest() { }
@Test @Tag("jenkins") // 替代 JUnit 4 @Category
public void jenkinsOnly() { }
@Test
public void windowsOnly() {
// 假設不滿足則跳過測試(非失敗)
Assumptions.assumeTrue(System.getenv("OS").startsWith("Windows"));
// 僅在 Windows 執行
}
}
@Disabled:停用測試@Tag:分類標籤,可配合建構工具篩選執行Assumptions.assumeTrue/assumeFalse/assumingThat:條件滿足才執行,支援 Lambda取代 @RunWith、@Rule、@ClassRule,支援多重擴展組合:
@ExtendWith(MockitoExtension.class)
@ExtendWith(CdiUnitExtension.class)
public class Test4 {
@Test
@DisplayName("awesome test")
void dependencyInjection(TestInfo testInfo) {
Assertions.assertEquals("awesome test", testInfo.getDisplayName());
}
}
@ExtendWith:註冊擴展,可重複標註TestInfo 注入:獲取測試中繼資料(顯示名稱、標籤等)JUnit 5 斷言為基礎,可無縫搭配第三方斷言庫:
@Test
public void emptyString() {
// JUnit 5
Assertions.assertTrue("".isEmpty());
// AssertJ
org.assertj.core.api.Assertions.assertThat("").isEmpty();
// Hamcrest
org.hamcrest.MatcherAssert.assertThat("", org.hamcrest.CoreMatchers.isEmptyString());
}