1
2
3
4
5 package com.qulice.pmd.rules;
6
7 import java.util.Arrays;
8 import net.sourceforge.pmd.lang.java.ast.ASTAnnotation;
9 import net.sourceforge.pmd.lang.java.ast.ASTExpression;
10 import net.sourceforge.pmd.lang.java.ast.ASTImportDeclaration;
11 import net.sourceforge.pmd.lang.java.ast.ASTMethodCall;
12 import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration;
13 import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule;
14
15
16
17
18
19
20 public final class ProhibitPlainJunitAssertionsRule
21 extends AbstractJavaRulechainRule {
22
23
24
25 private static final String[] PROHIBITED = {
26 "org.junit.Assert.assert",
27 "junit.framework.Assert.assert",
28 };
29
30 public ProhibitPlainJunitAssertionsRule() {
31 super(
32 ASTMethodDeclaration.class,
33 ASTImportDeclaration.class
34 );
35 }
36
37 @Override
38 public Object visit(final ASTImportDeclaration imp, final Object data) {
39 final String name = imp.getImportedName();
40 if (Arrays.stream(ProhibitPlainJunitAssertionsRule.PROHIBITED)
41 .anyMatch(name::contains)
42 ) {
43 asCtx(data).addViolation(imp);
44 }
45 return data;
46 }
47
48 @Override
49 public Object visit(final ASTMethodDeclaration method, final Object data) {
50 if (ProhibitPlainJunitAssertionsRule.isJUnitTest(method)) {
51 method.descendants(ASTMethodCall.class)
52 .filter(ProhibitPlainJunitAssertionsRule::isPlainJunitAssert)
53 .toStream()
54 .findAny()
55 .ifPresent(call -> asCtx(data).addViolation(method));
56 }
57 return data;
58 }
59
60 private static boolean isJUnitTest(final ASTMethodDeclaration method) {
61 return method.getDeclaredAnnotations()
62 .toStream()
63 .map(ASTAnnotation::getSimpleName)
64 .anyMatch(
65 name -> "Test".equals(name)
66 || "org.junit.Test".equals(name)
67 || "org.junit.jupiter.api.Test".equals(name)
68 );
69 }
70
71 private static boolean isPlainJunitAssert(final ASTMethodCall call) {
72 final String name = call.getMethodName();
73 final ASTExpression qualifier = call.getQualifier();
74 return name.startsWith("assert") && qualifier != null
75 && "Assert".contentEquals(qualifier.getText());
76 }
77 }