我的测试有很多共同的逻辑,所以我决定通过扩展来分享它。我写了两个类:TestNumberOne
which extends TestBase
.
TestBase.java
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
/**
* @author Pavel
* @since 2013-03-03
*/
public class TestBase {
@BeforeClass
public static void beforeClass() {
System.out.println("beforeClass() in TestBase");
System.out.flush();
}
@AfterClass
public static void afterClass() {
System.out.println("afterClass() in TestBase");
System.out.flush();
}
@Before
public void before() {
System.out.println("before() in TestBase");
System.out.flush();
}
@After
public void after() {
System.out.println("after() in TestBase");
System.out.flush();
}
}
TestNumberOne.java
import org.junit.*;
/**
* @author Pavel
* @since 2013-03-03
*/
public class TestNumberOne extends TestBase {
@Test
public void anyTest() {
System.out.println("anyTest() in TestNumberOne");
System.out.flush();
}
}
当我执行测试时,我得到了如此奇怪的输出:
before() in TestBase
anyTest() in TestNumberOne
after() in TestBase
beforeClass() in TestBase
afterClass() in TestBase
为什么它有如此奇怪的顺序?是否有任何扩展 JUnit 测试类的约定?
更新:
- 测试在 IDEA 中运行
- 为了得到如此奇怪的结果,我已经运行了几次(其他结果符合预期)