坑死我了,原来@Before会执行多次。
通过函数名可以实现顺序执行,执行顺序和函数的位置无关。
import org.junit.Before; import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class UnitTest { @Test public void testC() { System.out.println("testC"); } @Test public void testB() { System.out.println("testB"); } @Test public void testA() { System.out.println("testA"); } @Before public void testBefore() { System.out.println("before"); } @BeforeClass public static void testBeforeClass() { System.out.println("before class"); } }
运行结果
before class
before
testA
before
testB
before
testC