junit 构造函数在测试方法之后运行

junit constructor runs AFTER test methods

AFAIK 在任何方法之前,JRE 的构造函数方法是 运行。 但就我而言,构造函数是 运行ning 在测试方法之后。

import org.junit.*;
public class CourseTest {

    public CourseTest(){
        System.out.println("Constructor");
    }

    @BeforeClass
    public static void beforeClassTest() throws Exception{
        System.out.println("beforeClassTest");
    }

    @AfterClass
    public static void afterClassTest() throws Exception{
        System.out.println("afterClassTest");
    }

    @Before
    public void beforeTest() throws Exception{
        System.out.println("beforeTest");
    }

    @After
    public void afterTest() throws Exception{
        System.out.println("afterTest");
    }


    @Test
    public void getCredit() throws Exception {
        System.out.println("test 1 is getCredit");

    }

    @Test
    public void getName() throws Exception {
        System.out.println("test 2 is getName");
    }
}

结果是:

beforeTest
test 2 is getName
afterTest
beforeTest
test 1 is getCredit
afterTest
beforeClassTest
Constructor
Constructor
afterClassTest

不仅如此,我的测试用例也是 运行ning 的倒序。 对此很困惑。 我理解为什么构造函数 运行 两次,因为对于每个测试,都会实例化一个新的 class。但是构造函数怎么会在测试方法之后 运行s?

编辑: 正如@mike-jenkins 所建议的,我按以下顺序调试了测试 class 和 运行s:

1-beforeClassTest
2-Constructor
3-beforeTest
4-test 2 is getName
5-afterTest
6-Constructor
7-beforeTest
8-test 1 is getCredit
9-afterTest
10-afterClassTest

不保证 JUnit 测试的执行顺序,因为 JUnit 框架管理(内部)运行 并行测试。 这是为了加快测试执行速度,这在您在 CI(持续集成)环境中构建应用程序时特别有用,在这种环境中,整个过程中必须有数千个测试 运行申请.

如果你想控制执行顺序,你可以使用@FixMethodOrder注解如下:

 @FixMethodOrder(MethodSorters.NAME_ASCENDING)
 public class MyTest {
    //your test code here
 }

The default order of execution of JUnit tests within a class is deterministic but not predictable. The order of execution is not guaranteed for Java 7 (and some previous versions), and can even change from run to run, so the order of execution was changed to be deterministic (in JUnit 4.11)

你可以看看here

由于有多个测试用例,构造函数会被调用多次(由JUnit框架创建的不同线程并行执行)

由于多个线程 运行ning,构造函数的 System.out.prinln() (实际上是任何日志),不能保证它总是首先打印(即使它已被首先调用). 综上所述,在多线程环境中,您无法预测日志和 System.out.println() 语句的顺序。