为什么在执行子类测试方法时我的@BeforeClass 方法 运行 没有?

Why doesn't my @BeforeClass method run when executing a subclass test method?

我正在使用 IntelliJ IDEA CE 2018.3 和 JUnit 4.12。

我有一个测试 class 看起来像这样:

@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 运行 和 class 时,一切都按预期进行。但是,如果我只想 运行 itShouldDoSomething 测试(我通过设置一个针对 SomeOtherSubTestClass class 的 运行 配置来做), beforeAll 方法未执行。两个 before 方法都以正确的顺序执行,但静态 beforeAll 方法不是。

我是不是误会了什么,或者这是一个错误?

这不是错误。

beforeAll 方法是静态的,因此绑定到 class 而不是实例。这就是为什么在内部 classes 或子 classes.

中调用测试时不执行的原因

为了确保它被调用,您必须在每个内部 class 中定义一个 @BeforeClass 方法,然后在外部 class.[=12 上调用该方法=]