1、创建Order注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Order {
int value() default 0;
}
2、继承某个SpringRunner
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.InitializationError;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
import java.util.stream.Collectors;
public class OrderedRunner extends SpringJUnit4ClassRunner {
// test method list
private static List<FrameworkMethod> testMethodList;
public OrderedRunner(Class<?> clazz) throws InitializationError {
super(clazz);
}
@Override
protected List<FrameworkMethod> computeTestMethods() {
if (testMethodList == null) {
testMethodList = super.computeTestMethods().stream()
.sorted((m1, m2) -> {
Order o1 = m1.getAnnotation(Order.class);
Order o2 = m2.getAnnotation(Order.class);
if (o1 == null || o2 == null) {
return 0;
}
return o1.value() - o2.value();
}).collect(Collectors.toList());
}
return testMethodList;
}
}
这里继承的是SpringJUnit4ClassRunner,也可以是其他的Runner,比如说
BlockJUnit4ClassRunner等等。
而List<FrameworkMethod>是测试类的测试方法集合,通过重写computeTestMethods来对测试方法进行排序,从而让Junit test case有序执行。
3、测试
import com.scb.cdd.workflow.test.unit.junit.Order;
import com.scb.cdd.workflow.test.unit.junit.OrderedRunner;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
@Slf4j
@RunWith(OrderedRunner.class)
public class DemoTest {
@Test
@Order(1)
public void testB(){
log.info("B");
}
@Test
@Order(2)
public void testA(){
log.info("A");
}
@Test
@Order(3)
public void testC(){
log.info("C");
}
}
运行结果: B A C
后记
Junit测试实例的生命周期
Junit test为了保证隔离性,在每次执行测试方法之前都会通过反射创建一个新的测试类对象,这会导致测试类中的变量在每个测试方法中无法保持一致,既每个测试方法对该变量的修改都无法影响下一个测试方法的使用。
解决方法:为成员变量加static修饰符