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);

    }

 

JUnit5快速入门指南-2

 

优化方法:

public static void clear() {
    result = 0;
    System.out.println("当前结果已清零!");
}
JUnit5快速入门指南-2

 

repate设置测试的名称

@RepeatedTest(value = 10,name = "重复测试第{currentRepetition}次,共{totalRepetitions}次")
void countTest1() throws InterruptedException{
    int result =Calculator.count(1);
    System.out.println(result);
}
JUnit5快速入门指南-2

 

上面代码中*{currentRepetition}和{totalRepetitions}*表示对于当前重复和重复的总数中的占位符。

访问RepetitionInfo

@RepeatedTest(10)
void countTest2(RepetitionInfo repetitionInfo) throws InterruptedException{
    System.out.println("当前的次数 #" + repetitionInfo.getCurrentRepetition());
    assertEquals(3, repetitionInfo.getTotalRepetitions());
}
JUnit5快速入门指南-2

 

控制的输出(把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);
}
JUnit5快速入门指南-2

 

 

posted @ 2021-08-14 13:19  成子吃橙子  阅读(78)  评论(0编辑  收藏  举报