Why do JUnit 5 tests not inherit @Test annotation from abstract classes?

时光毁灭记忆、已成空白 提交于 2019-12-12 08:49:43

问题


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



来源:https://stackoverflow.com/questions/45162254/why-do-junit-5-tests-not-inherit-test-annotation-from-abstract-classes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!