Java 为什么';执行子类测试方法时是否运行my@BeforeClass方法?
我正在使用IntelliJ IDEA CE 2018.3和JUnit 4.12 我有一个这样的测试类:Java 为什么';执行子类测试方法时是否运行my@BeforeClass方法?,java,junit4,Java,Junit4,我正在使用IntelliJ IDEA CE 2018.3和JUnit 4.12 我有一个这样的测试类: @RunWith(HierarchicalContextRunner.class) public class TestClass { @BeforeClass public static void beforeAll() { //start a server for all tests to hit } @Before public void before() {
@RunWith(HierarchicalContextRunner.class)
public class TestClass {
@BeforeClass
public static void beforeAll() {
//start a server for all tests to hit
}
@Before
public void before() {
//init a common request object for each test
}
@Test
public void itShouldHaveSomeCommonProperty() {
//check some common thing
}
public class SomeSubTestClass {
@Before
public void before() {
//do some test case-specific setup
}
public class SomeOtherSubTestClass {
@Test
public void itShouldDoSomething() {
//hit the service and assert something about the result
}
}
}
}
当我告诉IntelliJ运行该类时,一切都按预期进行。但是,如果我只想运行itShouldDoSomething
测试(我通过设置一个针对SomeOtherSubTestClass
类的运行配置来执行),则不会执行beforeAll
方法。这两个before
方法都以正确的顺序执行,但静态before
方法没有执行
我是误解了什么,还是这是一个bug?这不是bug
beforeAll方法是静态的,因此绑定到类而不是实例。这就是为什么在内部类或子类中调用测试时不执行它的原因
为了确保调用它,您必须在每个内部类中定义一个
@BeforeClass
方法,然后在外部类上调用该方法。Argh。考虑到像预期的那样调用在方法之前封装的@。我觉得这是一个违反了最小惊讶原则的例子。不过,谢谢你的回答。