Skip to content

Commit a6526c6

Browse files
committed
Java: Replace ad-hoc TestClass detection.
1 parent dc7863c commit a6526c6

File tree

1 file changed

+21
-3
lines changed

1 file changed

+21
-3
lines changed

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

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,14 +36,32 @@ class TearDownMethod extends Method {
3636
}
3737
}
3838

39+
private class TestRelatedAnnotation extends Annotation {
40+
TestRelatedAnnotation() {
41+
this.getType().getPackage().hasName("org.testng.annotations") or
42+
this.getType().getPackage().hasName("org.junit") or
43+
this.getType().getPackage().hasName("org.junit.runner") or
44+
this.getType().getPackage().hasName("org.junit.jupiter.api") or
45+
this.getType().getPackage().hasName("org.junit.jupiter.params")
46+
}
47+
}
48+
49+
private class TestRelatedMethod extends Method {
50+
TestRelatedMethod() { this.getAnAnnotation() instanceof TestRelatedAnnotation }
51+
}
52+
3953
/**
40-
* A class detected to be a test class, either because it is a JUnit test class
41-
* or because its name or the name of one of its super-types contains the substring "Test".
54+
* A class detected to be a test class, either because it or one of its super-types
55+
* and/or enclosing types contains a test method or method with a unit-test-related
56+
* annotation.
4257
*/
4358
class TestClass extends Class {
4459
TestClass() {
4560
this instanceof JUnit38TestClass or
46-
this.getASupertype*().getSourceDeclaration().getName().matches("%Test%")
61+
exists(TestMethod m | m.getDeclaringType() = this) or
62+
exists(TestRelatedMethod m | m.getDeclaringType() = this) or
63+
this.getASourceSupertype() instanceof TestClass or
64+
this.getEnclosingType() instanceof TestClass
4765
}
4866
}
4967

0 commit comments

Comments
 (0)