[英]Why doesn't my @BeforeClass method run when executing a subclass test method?
I'm using IntelliJ IDEA CE 2018.3 and JUnit 4.12. 我正在使用IntelliJ IDEA CE 2018.3和JUnit 4.12。
I have a test class that looks like this: 我有一个看起来像这样的测试类:
@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
}
}
}
}
When I tell IntelliJ to run the class, everything works as expected. 当我告诉IntelliJ运行该类时,一切都按预期工作。 However, if I want to just run the
itShouldDoSomething
test (which I'm doing by setting up a run configuration that targets the SomeOtherSubTestClass
class), the beforeAll
method is not executed. 但是,如果我只想运行
itShouldDoSomething
测试(我通过设置针对SomeOtherSubTestClass
类的运行配置来完成此测试),则不会执行beforeAll
方法。 Both of the before
methods are executed in the correct order, but not the static beforeAll
method. 这两个
before
方法都以正确的顺序执行,但是静态的beforeAll
方法却没有。
Am I misunderstanding something, or is this a bug? 我是误解了什么,还是一个错误?
It is not a bug. 这不是错误。
The beforeAll
method is static and therefore tied to the class and not the instance. beforeAll
方法是静态的,因此绑定到类而不是实例。 This is why it is not executed when calling tests in inner classes or sub-classes. 这就是为什么在内部类或子类中调用测试时不执行它的原因。
To ensure it being called you would have to define a @BeforeClass
method in each of your inner classes which then call the method on the outer class. 为了确保它被调用,您必须在每个内部类中定义一个
@BeforeClass
方法,然后在外部类上调用该方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.