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?)
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();
}
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.");
}
}
With JUnit, you can write a test class for any source class in your Java project. Even abstract classes, which, as you know, can't be instantiated, but may have constructors for the benefit of “concrete” subclasses.
The Test annotation tells JUnit that the public void method to which it is attached can be run as a test case. To run the method, JUnit first constructs a fresh instance of the class then invokes the annotated method. Any exceptions thrown by the test will be reported by JUnit as a failure.
The @Test annotation is common for JUnit 4 as well as JUnit 5. The annotated methods represent the test cases in the class. There could be multiple methods each annotated with @Test in a JUnit class.
Unit testing an abstract class There are two options: Unit test all classes — When you test each class separately ( Student , Professor , and Person ) Unit test only concrete classes — When you test only the non-abstract classes ( Student and Professor )
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With