Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"ruleKey": "S1481",
"hasTruePositives": true,
"falseNegatives": 8,
"falseNegatives": 9,
"falsePositives": 0
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"ruleKey": "S2699",
"hasTruePositives": true,
"falseNegatives": 164,
"falseNegatives": 171,
"falsePositives": 1
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"ruleKey": "S3577",
"hasTruePositives": true,
"falseNegatives": 49,
"falseNegatives": 50,
"falsePositives": 0
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"ruleKey": "S5778",
"hasTruePositives": false,
"falseNegatives": 44,
"falseNegatives": 46,
"falsePositives": 0
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"ruleKey": "S9017",
"hasTruePositives": false,
"falseNegatives": 8,
"falsePositives": 0
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
package checks.tests;

import org.junit.jupiter.api.Test;
import org.mockito.stubbing.OngoingStubbing;

import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doCallRealMethod;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

class MockitoStubbingChainCheckSample {

interface UserRepository {
User findUser(long id);
void deleteUser(long id);
User saveUser(User user);
}

record User(String name) {}

@Test
void incompleteWhen() {
UserRepository repo = mock(UserRepository.class);
when(repo.findUser(42)); // Noncompliant {{Complete this stubbing by adding "thenReturn()", "thenThrow()", "thenAnswer()", or "thenCallRealMethod()".}}
//^^^^^^^^^^^^^^^^^^^^^^^
}

@Test
void completeWhen() {
UserRepository repo = mock(UserRepository.class);
when(repo.findUser(42)).thenReturn(new User("Alice")); // Compliant
when(repo.findUser(43)).thenThrow(new RuntimeException()); // Compliant
when(repo.findUser(44)).thenAnswer(inv -> new User("Bob")); // Compliant
when(repo.findUser(45)).thenCallRealMethod(); // Compliant
}

@Test
void incompleteDoMethods() {
UserRepository repo = mock(UserRepository.class);
doReturn(new User("Alice")); // Noncompliant {{Complete this stubbing by adding ".when(mock).method()".}}
//^^^^^^^^^^^^^^^^^^^^^^^^^^^
doThrow(new RuntimeException()); // Noncompliant {{Complete this stubbing by adding ".when(mock).method()".}} [[sc=5;ec=36]]
doAnswer(inv -> null); // Noncompliant {{Complete this stubbing by adding ".when(mock).method()".}}
doNothing(); // Noncompliant {{Complete this stubbing by adding ".when(mock).method()".}}
doCallRealMethod(); // Noncompliant {{Complete this stubbing by adding ".when(mock).method()".}}
}

@Test
void incompleteDoChainMissingMethodCall() {
UserRepository repo = mock(UserRepository.class);
doThrow(new RuntimeException()).when(repo); // Noncompliant {{Complete this stubbing by adding the method to stub.}}
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
}

@Test
void completeDoMethods() {
UserRepository repo = mock(UserRepository.class);
doReturn(new User("Alice")).when(repo).findUser(42); // Compliant
doThrow(new RuntimeException()).when(repo).deleteUser(99); // Compliant
doAnswer(inv -> new User("Bob")).when(repo).saveUser(new User("Bob")); // Compliant
doNothing().when(repo).deleteUser(1); // Compliant
doCallRealMethod().when(repo).findUser(1); // Compliant
}

@Test
void whenStoredInVariable() {
UserRepository repo = mock(UserRepository.class);
OngoingStubbing<User> stub = when(repo.findUser(42)); // Compliant - variable declaration skipped
stub.thenReturn(new User("Alice"));
}

@Test
void whenStoredViaAssignment() {
UserRepository repo = mock(UserRepository.class);
OngoingStubbing<User> stub;
stub = when(repo.findUser(42)); // Compliant - assignment expression skipped
stub.thenReturn(new User("Alice"));
}

@Test
void incompleteWhenInsideLambda() {
UserRepository repo = mock(UserRepository.class);
org.junit.jupiter.api.Assertions.assertThrows(RuntimeException.class, () -> {
when(repo.findUser(1)); // Noncompliant {{Complete this stubbing by adding "thenReturn()", "thenThrow()", "thenAnswer()", or "thenCallRealMethod()".}}
});
}

@Test
void completeWhenInsideLambda() {
UserRepository repo = mock(UserRepository.class);
org.junit.jupiter.api.Assertions.assertThrows(RuntimeException.class, () -> {
when(repo.findUser(1)).thenReturn(new User("Alice")); // Compliant
});
}

OngoingStubbing<User> helperMethod(UserRepository repo) {
return when(repo.findUser(42)); // Compliant - return statement skipped
}
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
/*
* SonarQube Java
* Copyright (C) SonarSource Sàrl
* mailto:info AT sonarsource DOT com
*
* You can redistribute and/or modify this program under the terms of
* the Sonar Source-Available License Version 1, as published by SonarSource Sàrl.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the Sonar Source-Available License for more details.
*
* You should have received a copy of the Sonar Source-Available License
* along with this program; if not, see https://sonarsource.com/license/ssal/
*/
package org.sonar.java.checks.tests;

import org.sonar.check.Rule;
import org.sonar.plugins.java.api.JavaFileScanner;
import org.sonar.plugins.java.api.JavaFileScannerContext;
import org.sonar.plugins.java.api.semantic.MethodMatchers;
import org.sonar.plugins.java.api.tree.AssignmentExpressionTree;
import org.sonar.plugins.java.api.tree.BaseTreeVisitor;
import org.sonar.plugins.java.api.tree.BlockTree;
import org.sonar.plugins.java.api.tree.ExpressionTree;
import org.sonar.plugins.java.api.tree.LambdaExpressionTree;
import org.sonar.plugins.java.api.tree.MemberSelectExpressionTree;
import org.sonar.plugins.java.api.tree.MethodInvocationTree;
import org.sonar.plugins.java.api.tree.ReturnStatementTree;
import org.sonar.plugins.java.api.tree.VariableTree;

@Rule(key = "S9017")
public class MockitoStubbingChainCheck extends BaseTreeVisitor implements JavaFileScanner {

private static final String WHEN_MESSAGE = "Complete this stubbing by adding \"thenReturn()\", \"thenThrow()\", \"thenAnswer()\", or \"thenCallRealMethod()\".";
private static final String DO_MESSAGE = "Complete this stubbing by adding \".when(mock).method()\".";
private static final String STUBBER_WHEN_MESSAGE = "Complete this stubbing by adding the method to stub.";

private static final MethodMatchers MOCKITO_WHEN = MethodMatchers.create()
.ofTypes("org.mockito.Mockito")
.names("when")
.withAnyParameters()
.build();

private static final MethodMatchers MOCKITO_DO_METHODS = MethodMatchers.create()
.ofTypes("org.mockito.Mockito")
.names("doReturn", "doThrow", "doAnswer", "doNothing", "doCallRealMethod")
.withAnyParameters()
.build();

// Detects do*().when(mock) that is not followed by a method call on the mock
private static final MethodMatchers STUBBER_WHEN = MethodMatchers.create()
.ofSubTypes("org.mockito.stubbing.Stubber")
.names("when")
.withAnyParameters()
.build();

private JavaFileScannerContext context;

@Override
public void scanFile(JavaFileScannerContext context) {
if (context.getSemanticModel() == null) {
return;
}
this.context = context;
scan(context.getTree());
}

@Override
public void visitVariable(VariableTree tree) {
// skip: the stub may be stored in a variable and completed later
}
Comment thread
gitar-bot[bot] marked this conversation as resolved.

@Override
public void visitAssignmentExpression(AssignmentExpressionTree tree) {
// skip: the stub may be stored in a pre-declared variable and completed later
}

@Override
public void visitReturnStatement(ReturnStatementTree tree) {
// skip: returning a partial stub is valid (e.g. helper methods)
}

@Override
public void visitMethodInvocation(MethodInvocationTree mit) {
visitMethodInvocation(mit, false);
// also check stubs inside block-bodied lambda arguments (e.g. assertThrows(() -> { when(...); }))
for (ExpressionTree arg : mit.arguments()) {
if (arg instanceof LambdaExpressionTree lambda
&& lambda.body() instanceof BlockTree block) {
visitBlock(block);
}
}
}

private void visitMethodInvocation(MethodInvocationTree mit, boolean isChained) {
if (!isChained && isIncompleteStubbing(mit)) {
return;
}
if (mit.methodSelect() instanceof MemberSelectExpressionTree mset
&& mset.expression() instanceof MethodInvocationTree innerMit) {
visitMethodInvocation(innerMit, true);
}
}

private boolean isIncompleteStubbing(MethodInvocationTree mit) {
if (MOCKITO_WHEN.matches(mit)) {
context.reportIssue(this, mit, WHEN_MESSAGE);
return true;
}
if (MOCKITO_DO_METHODS.matches(mit)) {
context.reportIssue(this, mit, DO_MESSAGE);
return true;
}
if (STUBBER_WHEN.matches(mit)) {
context.reportIssue(this, mit, STUBBER_WHEN_MESSAGE);
return true;
}
return false;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/*
* SonarQube Java
* Copyright (C) SonarSource Sàrl
* mailto:info AT sonarsource DOT com
*
* You can redistribute and/or modify this program under the terms of
* the Sonar Source-Available License Version 1, as published by SonarSource Sàrl.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the Sonar Source-Available License for more details.
*
* You should have received a copy of the Sonar Source-Available License
* along with this program; if not, see https://sonarsource.com/license/ssal/
*/
package org.sonar.java.checks.tests;

import org.junit.jupiter.api.Test;
import org.sonar.java.checks.verifier.CheckVerifier;

import static org.sonar.java.checks.verifier.TestUtils.testCodeSourcesPath;

class MockitoStubbingChainCheckTest {

@Test
void test() {
CheckVerifier.newVerifier()
.onFile(testCodeSourcesPath("checks/tests/MockitoStubbingChainCheckSample.java"))
.withCheck(new MockitoStubbingChainCheck())
.verifyIssues();
}

@Test
void testWithoutSemantics() {
CheckVerifier.newVerifier()
.onFile(testCodeSourcesPath("checks/tests/MockitoStubbingChainCheckSample.java"))
.withCheck(new MockitoStubbingChainCheck())
.withoutSemantic()
.verifyNoIssues();
}
}
Loading
Loading