1. 程式人生 > 其它 >JUnit5快速入門指南-2

JUnit5快速入門指南-2

重複測試中容易產生的問題

 //結果類
private static int result = 0;
public static int count(int x) throws InterruptedException {
    int i = result;
    sleep(1000);
    result = i + x;
    return result;
}
// 呼叫以上方法多執行緒測試
    @RepeatedTest(10)
    void countTest() throws InterruptedException{
        int result = Calculator.count(1);
        System.out.println(result);
              assertEquals(1,result);

    }

優化方法:

public static void clear() {
    result = 0;
    System.out.println("當前結果已清零!");
}

repate設定測試的名稱

@RepeatedTest(value = 10,name = "重複測試第{currentRepetition}次,共{totalRepetitions}次")
void countTest1() throws InterruptedException{
    int result =Calculator.count(1);
    System.out.println(result);
}

上面程式碼中*{currentRepetition}和{totalRepetitions}*表示對於當前重複和重複的總數中的佔位符。

訪問RepetitionInfo

@RepeatedTest(10)
void countTest2(RepetitionInfo repetitionInfo) throws InterruptedException{
    System.out.println("當前的次數 #" + repetitionInfo.getCurrentRepetition());
    assertEquals(3, repetitionInfo.getTotalRepetitions());
}

控制的輸出(把before和after的輸出去掉了):

計算器的多執行緒測試

@RepeatedTest(value = 10,name = "重複執行10次的加法測試,當前第{currentRepetition}次,共{totalRepetitions}次")
public void add(){
    int result= Calculator.add(4,2);
    System.out.println(result);
    assertEquals(6,result);
}