※常用方法
@Test
public void xxx() {
int a = 25;
int b = 15;
// Assertions.assertEquals(a, b);
// Assertions.assertEquals(a, b, "我錯了");
// Assertions.assertEquals(a, b, () -> "我死了");
Assertions.assertEquals(a, b, () -> {
if (a > b) {
return "a大於b";
}
return "a小於b";
});
}
@Test
public void ooo() {
String rtn = Assertions.assertTimeout(Duration.ofMillis(1000), () -> {
Thread.sleep(1500);
System.out.println("超時也會印出");
return "完成時印出";
});
// String rtn = Assertions.assertTimeoutPreemptively(Duration.ofMillis(1000), () -> {
// Thread.sleep(1500);
// System.out.println("超時不會印出");
// return "完成時印出";
// });
System.out.println(rtn);
}
@Test
public void zzz() {
ArithmeticException ari = Assertions.assertThrows(ArithmeticException.class, () -> {
int rtn = 1 / 0;
});
System.out.println(ari.getMessage());
}
※assertTimeoutPreemptively 的 preempt 有先發制人的意思,一 timeout 就結束了,所以後面的程式不會執行
※通常 overloading 方法,最後有一個 String,是錯誤時顯示在圖形裡的,JUnit4 是第一個參數,而 JUnit5 還可以用 java8 的 Supplier
※@DisplayName、@RepeatedTest
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.Test;
@DisplayName("這樣而已")
public class AppTest2 {
@Test
@RepeatedTest(3) // 加跑幾次
public void xxx() {
System.out.println("x");
}
@Test
@DisplayName("哇哈哈")
public void ooo() {
System.out.println("o");
}
}
※@RepeatedTest 裡的數字是「加跑」幾次的意思
※@DisplayName 要看圖形,如下:
※條件測試
@EnabledOnOs({ OS.WINDOWS, OS.LINUX })
// @DisabledOnOs({ OS.WINDOWS, OS.LINUX })
@EnabledIfSystemProperty(named = "user.language", matches = "en")
// @DisabledIfSystemProperty(named = "user.language", matches = "en")
@Test
public void testXxx() {
System.out.println("xxx");
}
※可以使用 System.getProperties().list(System.out) 偷看一下
※目前版本是 5.1.1,還有一些 annotation 在實驗的階段

沒有留言:
張貼留言