Skip to content

Commit 4d7bed6

Browse files
Jami CogswellJami Cogswell
authored andcommitted
Java: exclude anonymous, local, and private classes
1 parent 3e13f0e commit 4d7bed6

File tree

3 files changed

+43
-3
lines changed

3 files changed

+43
-3
lines changed

java/ql/lib/semmle/code/java/UnitTests.qll

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,20 @@ class JUnit5TestClass extends Class {
120120
JUnit5TestClass() { this.getAMethod() instanceof JUnitJupiterTestMethod }
121121
}
122122

123+
/**
124+
* A JUnit inner test class that is non-anonymous, non-local,
125+
* and non-private.
126+
*/
127+
class JUnit5InnerTestClass extends JUnit5TestClass {
128+
JUnit5InnerTestClass() {
129+
// `InnerClass` is a non-static nested class.
130+
this instanceof InnerClass and
131+
not this.isAnonymous() and
132+
not this.isLocal() and
133+
not this.isPrivate()
134+
}
135+
}
136+
123137
/**
124138
* A JUnit `@Ignore` annotation.
125139
*/

java/ql/src/Likely Bugs/Frameworks/JUnit/JUnit5MissingNestedAnnotation.ql

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,8 @@
1515

1616
import java
1717

18-
from JUnit5TestClass testClass
18+
from JUnit5InnerTestClass testClass
1919
where
20-
// `InnerClass` is a non-static, nested class.
21-
testClass instanceof InnerClass and
2220
not testClass.hasAnnotation("org.junit.jupiter.api", "Nested") and
2321
// An abstract class should not have a `@Nested` annotation
2422
not testClass.isAbstract()

java/ql/test/query-tests/Likely Bugs/Frameworks/JUnit/AnnotationTest.java

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,4 +59,32 @@ public abstract class Test8 {
5959
public void test() {
6060
}
6161
}
62+
63+
interface Test9 {
64+
}
65+
66+
public void f() {
67+
// COMPLIANT: anonymous classes are not considered as inner test
68+
// classes by JUnit and therefore don't need `@Nested`
69+
new Test9() {
70+
@Test
71+
public void test() {
72+
}
73+
};
74+
// COMPLIANT: local classes are not considered as inner test
75+
// classes by JUnit and therefore don't need `@Nested`
76+
class Test10 {
77+
@Test
78+
void test() {
79+
}
80+
}
81+
}
82+
83+
// COMPLIANT: private classes are not considered as inner test
84+
// classes by JUnit and therefore don't need `@Nested`
85+
private class Test11 {
86+
@Test
87+
public void test() {
88+
}
89+
}
6290
}

0 commit comments

Comments
 (0)