-
Notifications
You must be signed in to change notification settings - Fork 725
SONARJAVA-6605 Implement S9017: Mockito stubbing chains should be complete #5782
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
5f685fc
generate doc for S9017
NoemieBenard 54abfd8
implement rule
NoemieBenard 15f58d7
update rule metadata
NoemieBenard 5fa2cf2
address review comments
NoemieBenard 33a60d8
fix autoscan
NoemieBenard dd0611a
fix autoscan
NoemieBenard 5f777a1
address review comment
NoemieBenard 01ed929
remove redundant isChained parameter and check
NoemieBenard File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,6 @@ | ||
| { | ||
| "ruleKey": "S1481", | ||
| "hasTruePositives": true, | ||
| "falseNegatives": 8, | ||
| "falseNegatives": 9, | ||
| "falsePositives": 0 | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,6 @@ | ||
| { | ||
| "ruleKey": "S2699", | ||
| "hasTruePositives": true, | ||
| "falseNegatives": 164, | ||
| "falseNegatives": 171, | ||
| "falsePositives": 1 | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,6 @@ | ||
| { | ||
| "ruleKey": "S3577", | ||
| "hasTruePositives": true, | ||
| "falseNegatives": 49, | ||
| "falseNegatives": 50, | ||
| "falsePositives": 0 | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,6 @@ | ||
| { | ||
| "ruleKey": "S5778", | ||
| "hasTruePositives": false, | ||
| "falseNegatives": 44, | ||
| "falseNegatives": 46, | ||
| "falsePositives": 0 | ||
| } |
6 changes: 6 additions & 0 deletions
6
its/autoscan/src/test/resources/autoscan/diffs/diff_S9017.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| { | ||
| "ruleKey": "S9017", | ||
| "hasTruePositives": false, | ||
| "falseNegatives": 8, | ||
| "falsePositives": 0 | ||
| } |
103 changes: 103 additions & 0 deletions
103
...ecks-test-sources/default/src/test/java/checks/tests/MockitoStubbingChainCheckSample.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| } | ||
| } | ||
|
|
122 changes: 122 additions & 0 deletions
122
java-checks/src/main/java/org/sonar/java/checks/tests/MockitoStubbingChainCheck.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| } | ||
|
|
||
| @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; | ||
| } | ||
| } | ||
42 changes: 42 additions & 0 deletions
42
java-checks/src/test/java/org/sonar/java/checks/tests/MockitoStubbingChainCheckTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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(); | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.