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

Lee Crabtree :

I'm using IntelliJ IDEA CE 2018.3 and 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. 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. Both of the before methods are executed in the correct order, but not the static beforeAll method.

Am I misunderstanding something, or is this a bug?

hotzst :

It is not a bug.

The beforeAll method is static and therefore tied to the class and not the instance. 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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=146344&siteId=1