Why do JUnit 5 tests not inherit @Test annotation

2019-04-29 12:29发布

问题:

I just realized (while migrating legacy code from JUnit 4 to JUnit 5) that some of our test methods are not executed because they don't have the @Test annotation. They don't have it, because they override methods from an abstract superclass (where the annotation is present).

I can easily fix this by adding the @Test to each method. But I was wondering if this is intended behavior. It changed from JUnit 4 to 5 but I can't find anything about it in the official JUnit5 User Guide or anywhere else.

According to this question, Annotations are usually not inherited. But it seems that this was deliberately changed in the new JUnit version. (Or am I missing something?)

The abstract test class

import org.junit.jupiter.api.Test;

abstract class AbstractJUnit5Test {

  @Test
  void generalTest() {
    System.out.println("This is a test in the abstract class");
  }

  @Test
  abstract void concreteTest();
}

The concrete test class

import org.junit.jupiter.api.Test;

class ConcreteJUnt5Test extends AbstractJUnit5Test {

  // only gets executed with an additional @Test annotation:
  @Override
  void concreteTest() { 
    System.out.println("This is from the concrete test method.");
  }
}

回答1:

That's an unintentional difference between JUnit 4 and JUnit Jupiter.

See details at https://github.com/junit-team/junit5/issues/960

Edit: after further investigation it seems that this (convenient) behavior from JUnit 4 is actually unintended. See Sam's latest comment at https://github.com/junit-team/junit5/issues/960#issuecomment-316114648



回答2:

I suppose you are trying to build some sort of relationship among your test methods. Try if you can use @Nested.
You can find a sample here