junit4按顺序执行test方法

来源:互联网 发布:沈阳纳森网络干什么的 编辑:程序博客网 时间:2024/06/06 01:25

junit4按顺序执行test方法

很多情况下,写了一堆的test case,希望某一些test case必须在某个test case之后执行。比如,测试某一个Dao代码,希望添加的case在最前面,然后是修改或者查询,最后才是删除,以前的做法把所有的方法都集中到某一个方法去执行,一个个罗列好,比较麻烦。比较幸福的事情就是JUnit4.11之后提供了MethodSorters,可以有三种方式对test执行顺序进行指定,如下:

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

使用DEFAULT方式:

package com.netease.test.junit;import org.apache.log4j.Logger;import org.junit.FixMethodOrder;import org.junit.Test;import org.junit.runners.MethodSorters;/** * User: hzwangxx * Date: 14-3-31 * Time: 15:35 */@FixMethodOrder(MethodSorters.DEFAULT)public class TestOrder {    private static final Logger LOG = Logger.getLogger(TestOrder.class);    @Test    public void testFirst() throws Exception {        LOG.info("------1--------");    }    @Test    public void testSecond() throws Exception {        LOG.info("------2--------");    }    @Test    public void testThird() throws Exception {        LOG.info("------3--------");    }}/*output:2014-03-31 16:04:15,984 0    [main] INFO  - ------1--------2014-03-31 16:04:15,986 2    [main] INFO  - ------3--------2014-03-31 16:04:15,987 3    [main] INFO  - ------2--------*/

换成按字母排序

package com.netease.test.junit;import org.apache.log4j.Logger;import org.junit.FixMethodOrder;import org.junit.Test;import org.junit.runners.MethodSorters;/** * User: hzwangxx * Date: 14-3-31 * Time: 15:35 */@FixMethodOrder(MethodSorters.NAME_ASCENDING)public class TestOrder {    private static final Logger LOG = Logger.getLogger(TestOrder.class);    @Test    public void testFirst() throws Exception {        LOG.info("------1--------");    }    @Test    public void testSecond() throws Exception {        LOG.info("------2--------");    }    @Test    public void testThird() throws Exception {        LOG.info("------3--------");    }}/*2014-03-31 16:10:25,360 0    [main] INFO  - ------1--------2014-03-31 16:10:25,361 1    [main] INFO  - ------2--------2014-03-31 16:10:25,362 2    [main] INFO  - ------3--------*/

多个test执行顺序

按照设计,Junit不指定test方法的执行顺序。

到目前为止,这些test方法仍是简单地根据反射API返回的顺序来执行。

但是,由于Java平台并不能指定明确的顺序,因此使用JVM来决定test方法的顺序是不明智的。

而事实上,JDK7会返回一个随机的顺序。

当然,编写完善的测试代码并不需要假定任何执行顺序,但是另一些需要,而且在一些特定平台上一个可预测的错误总比随机错误要好。

从4.11版本开始,JUnit将会默认使用一个可确定,但是不可预测的顺序(MethodSorters.DEFAULT)。

如果你想要改变test的执行顺序,那么你可以简单的在test类上加以个注解@FixMethodOrder 并且指定一个合适的MethodSorters

@FixMethodOrder(MethodSorters.JVM) : 根据JVM返回的顺序来决定test方法的执行顺序。每次测试这个顺序可能都不一样

@FixMethodOrder(MethodSorters.NAME_ASCENDING) : 根据test方法名按照字典顺序升序排序

注:1、Junit4.11版本及以后才支持 2、使用Junit,需要有配合的hamcrest包

0 0