好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

JUnit测试控制@Test执行顺序的三种方式小结

JUnit测试控制@Test执行顺序

第一种

?

1

@FixMethodOrder (MethodSorters.JVM)

从上到下 执行@Test

第二种(推荐)

?

1

@FixMethodOrder (MethodSorters.NAME_ASCENDING)

按方法名字顺序执行@Test

第三种

?

1

@FixMethodOrder (MethodSorters.DEFAULT)

默认方法,不可预期

Junit测试方法保证执行顺序

由于需要做自动化测试,所以需要比较完善的单元测试。但是又因为某些测试的执行依赖另外一个测试产生的结果,所以希望所写的test case按照自己希望的顺序来执行。

随后博主查阅资料发现了FixMethodOrder注解,可以有三种方式可以控制test执行顺序。

?

1

2

3

4

5

6

7

8

9

10

11

12

/**

    * Sorts the test methods by the method name, in lexicographic order, with {@link Method#toString()} used as a tiebreaker

    */

   NAME_ASCENDING(MethodSorter.NAME_ASCENDING),

   /**

    * Leaves the test methods in the order returned by the JVM. Note that the order from the JVM may vary from run to run

    */

   JVM( null ),

   /**

    * Sorts the test methods in a deterministic, but not predictable, order

    */

   DEFAULT(MethodSorter.DEFAULT);

大概上就是上面三种,很多大佬的博客上都对这几种有讲解以及示例,博主在这里就不啰嗦了,下面说一下我的一些疑问以及发现。

当使用默认排序时

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

@FixMethodOrder (MethodSorters.DEFAULT)

public class testDemo{

    

     @Test

     public void B(){

         System.out.println( "b" );

     }

     @Test

     public void C(){

         System.out.println( "c" );

     }

     @Test

     public void A(){

         System.out.println( "a" );

     }

     @Test

     public void AB(){

         System.out.println( "ab" );

     }

     @Test

     public void AC(){

         System.out.println( "ac" );

     }

     @Test

     public void A1(){

         System.out.println( "a1" );

     }

}

输出

a
b
c
a1
ab
ac

这只是博主众多测试结果中的一个,实际上与API中描述的[but not predictable]有所出入,执行的顺序是可预期的。

因为观察到,名字短的总排在前面,ascii码小的总在前面,所以博主猜测有可能顺序跟方法名字的字符串的hashcode有关的,于是加上hashcode方法输出之后,得到结果:

方法A:65
方法B:66
方法C:67
方法A1:2064
方法AB:2081
方法AC:2082

所以可以得出结论,当单元测试使用默认执行顺序的时候,测试方法执行的顺序是跟测试方法名字符串的hashcode大小线性相关。

Junit执行时应该是把所有的有@test注释的方法存到一个容器里,然后交由jvm去一一执行(博主还没来得及仔细去研读Junit的源码,这是本人的猜测)。那么问题来了,这一系列的方法是在同一个线程下还是多个线程一起执行的呢?

其实从测试的执行顺序可以控制不难猜出,多个测试方法是串行执行的,但是实践才是检验真理的唯一标准。

代码就不贴了,有兴趣的同学可以自己写一下看看,就是在第二顺位执行的方法那里让他休眠一下,观察是否也会阻塞第三个方法。

最终的结果也证明了猜想。

我现在看的还比较浅显,有时间的话会去研读Junit的底层源码。以上为个人经验,希望能给大家一个参考,也希望大家多多支持

原文链接:https://blog.csdn.net/baidu_38837718/article/details/104415160

查看更多关于JUnit测试控制@Test执行顺序的三种方式小结的详细内容...

  阅读:33次