Java: exclude abstract classes

This commit is contained in:
Jami Cogswell
2025-03-21 16:11:11 -04:00
parent b08c8d020d
commit ed57bc7858
3 changed files with 27 additions and 3 deletions

View File

@@ -47,11 +47,18 @@ public class IntegerOperationTest {
## Implementation Notes
The `@Nested` annotation does not apply to inner static classes, since the meaning of the annotation is to mark a class as "a *non-static* inner class containing `@Test` methods to be picked up by a build system". Therefore, this rule does not aim to target static inner test classes with a `@Nested` annotation, nor does it try to enforce such correct usage of `@Nested`. Therefore, any code that resembles below is not non-compliant to this rule.
The `@Nested` annotation does not apply to inner static classes, since the meaning of the annotation is to mark a class as "a *non-static* inner class containing `@Test` methods to be picked up by a build system". It also does not apply to inner abstract classes since there is no use case for an `@Nested` annotation on an abstract class. Therefore, this rule does not aim to target static or abstract inner test classes with a `@Nested` annotation, nor does it try to enforce such correct usage of `@Nested`. Therefore, any code that resembles the below is not non-compliant to this rule.
``` java
@Nested
public static class Test6 { // COMPLIANT: Although invalid, this matter is out of the scope
public static class TestStatic { // COMPLIANT: Although invalid, this matter is out of the scope
@Test
public void test() {
}
}
@Nested
public abstract class TestAbstract { // COMPLIANT: Although invalid, this matter is out of the scope
@Test
public void test() {
}

View File

@@ -18,5 +18,7 @@ from JUnit5TestClass testClass
where
// `InnerClass` is a non-static, nested class.
testClass instanceof InnerClass and
not testClass.hasAnnotation("org.junit.jupiter.api", "Nested")
not testClass.hasAnnotation("org.junit.jupiter.api", "Nested") and
// An abstract class should not have a `@Nested` annotation
not testClass.isAbstract()
select testClass, "This JUnit5 inner test class lacks a '@Nested' annotation."

View File

@@ -44,4 +44,19 @@ public class AnnotationTest {
public void test() {
}
}
public abstract class Test7 { // COMPLIANT: Abstract inner test classes don't need `@Nested`
@Test
public void test() {
}
}
// COMPLIANT: Invalid to use `@Nested` on an abstract class, but
// this matter is out of scope (see QHelp Implementation Notes)
@Nested
public abstract class Test8 {
@Test
public void test() {
}
}
}