Skip to content

Commit 4f0ccff

Browse files
committed
Add Mockito-ArgumentMatchers-parameterized-call.ql
1 parent f79c5ca commit 4f0ccff

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* Finds usage of Mockito's `ArgumentMatchers` methods where type arguments
3+
* are explicitly provided. If the type arguments are not constrained by
4+
* a method argument (e.g. `Class<T>`) they have no effect at runtime and
5+
* can be confusing, giving the false expression that Mockito will only
6+
* match the specified types.
7+
*
8+
* Instead the type arguments should be omitted; the compiler will then
9+
* infer them.
10+
*
11+
* For example:
12+
* ```java
13+
* // Error-prone: Looks as if this only matches String, but it actually
14+
* // matches anything
15+
* // Should instead just use `Mockito.any()`, or `Mockito.anyString()`
16+
* verify(myObj).doSomething(Mockito.<String>any());
17+
* ```
18+
*
19+
* @kind problem
20+
* @id TODO
21+
*/
22+
23+
import java
24+
25+
from MethodAccess matcherCall, Method matcherMethod, Expr typeArg
26+
where
27+
matcherCall.getMethod().getSourceDeclaration() = matcherMethod and
28+
matcherMethod.getDeclaringType().hasQualifiedName("org.mockito", "ArgumentMatchers") and
29+
// There is no method parameter which could restrict the type argument (e.g. `Class<T>`)
30+
matcherMethod.hasNoParameters() and
31+
// Explicitly specifies type arguments, instead of letting the compiler infer them
32+
typeArg = matcherCall.getATypeArgument() and
33+
// Ignore if type arguments are needed to select the correct overload
34+
not exists(MethodAccess stubbedCall, Method stubbedMethod, int argIndex, SrcMethod overload |
35+
stubbedCall.getMethod().getSourceDeclaration() = stubbedMethod and
36+
stubbedCall.getArgument(argIndex) = matcherCall and
37+
overload.getDeclaringType() =
38+
stubbedCall.getReceiverType().getSourceDeclaration().getASourceSupertype*() and
39+
overload.getName() = stubbedMethod.getName() and
40+
overload.getNumberOfParameters() = stubbedMethod.getNumberOfParameters() and
41+
overload.getParameterType(argIndex) != stubbedMethod.getParameterType(argIndex) and
42+
overload != stubbedMethod and
43+
not overload.isPrivate()
44+
)
45+
select typeArg, "Explicit type argument should be omitted because it can be misleading"

0 commit comments

Comments
 (0)