Skip to content
Open
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": "S2699",
"hasTruePositives": true,
"falseNegatives": 171,
"falseNegatives": 174,
"falsePositives": 1
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"ruleKey": "S3577",
"hasTruePositives": true,
"falseNegatives": 50,
"falseNegatives": 51,
"falsePositives": 0
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"ruleKey": "S9016",
"hasTruePositives": false,
"falseNegatives": 1,
"falsePositives": 0
}
21 changes: 21 additions & 0 deletions its/ruling/src/test/resources/sonar-server/java-S9016.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"org.sonarsource.sonarqube:sonar-server:src/test/java/org/sonar/server/app/TomcatContextsTest.java": [
60
],
"org.sonarsource.sonarqube:sonar-server:src/test/java/org/sonar/server/authentication/OAuth2CallbackFilterTest.java": [
75
],
"org.sonarsource.sonarqube:sonar-server:src/test/java/org/sonar/server/issue/ws/ComponentTagsActionTest.java": [
93,
117
],
"org.sonarsource.sonarqube:sonar-server:src/test/java/org/sonar/server/plugins/StaticResourcesServletTest.java": [
145
],
"org.sonarsource.sonarqube:sonar-server:src/test/java/org/sonar/server/rule/RegisterRulesTest.java": [
486
],
"org.sonarsource.sonarqube:sonar-server:src/test/java/org/sonar/server/rule/WebServerRuleFinderImplTest.java": [
41
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package checks.tests;

import org.junit.jupiter.api.Test;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

class MockitoInlineMockInThenReturnCheckSample {

interface Foo {
String method();
}

class MyClass {
Foo foo() {
return null;
}
}

@Test
void noncompliantInlineMock() {
MyClass myMock = mock(MyClass.class);
when(myMock.foo()).thenReturn(mock(Foo.class)); // Noncompliant {{Extract this mock creation to a local variable.}}
// ^^^^^^^^^^^^^^^
}

@Test
void compliantExtractedMock() {
MyClass myMock = mock(MyClass.class);
Foo fooMock = mock(Foo.class);
when(myMock.foo()).thenReturn(fooMock); // Compliant
}

@Test
void compliantLiteralArg() {
MyClass myMock = mock(MyClass.class);
when(myMock.foo()).thenReturn(null); // Compliant
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
/*
* 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.BaseTreeVisitor;
import org.sonar.plugins.java.api.tree.ExpressionTree;
import org.sonar.plugins.java.api.tree.MethodInvocationTree;
import org.sonar.plugins.java.api.tree.Tree;

@Rule(key = "S9016")
public class MockitoInlineMockInThenReturnCheck extends BaseTreeVisitor implements JavaFileScanner {

private static final String MESSAGE = "Extract this mock creation to a local variable.";

private static final MethodMatchers THEN_RETURN = MethodMatchers.create()
.ofSubTypes("org.mockito.stubbing.OngoingStubbing")
.names("thenReturn")
.withAnyParameters()
.build();

private static final MethodMatchers MOCKITO_MOCK = MethodMatchers.create()
.ofTypes("org.mockito.Mockito")
.names("mock")
.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 visitMethodInvocation(MethodInvocationTree mit) {
if (THEN_RETURN.matches(mit)) {
for (ExpressionTree arg : mit.arguments()) {
if (arg.is(Tree.Kind.METHOD_INVOCATION) && MOCKITO_MOCK.matches((MethodInvocationTree) arg)) {
context.reportIssue(this, arg, MESSAGE);
}
}
}
super.visitMethodInvocation(mit);
}
}
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 MockitoInlineMockInThenReturnCheckTest {

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

@Test
void testWithoutSemantics() {
CheckVerifier.newVerifier()
.onFile(testCodeSourcesPath("checks/tests/MockitoInlineMockInThenReturnCheckSample.java"))
.withCheck(new MockitoInlineMockInThenReturnCheck())
.withoutSemantic()
.verifyNoIssues();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
<p>This is an issue when using mocking framework stubbing syntax to specify return values and creating a mock object directly as an argument to the
return value specification method.</p>
<p>In Java with Mockito, this specifically refers to inlining the mock creation inside the <code>thenReturn()</code> method.</p>
<h2>Why is this an issue?</h2>
<p>Mocking frameworks use an internal state machine to track stubbing operations and validate that they are completed correctly. When you create a
mock object inline within a return value specification, the framework registers the mock creation as a new event before it finishes recording the
stubbing chain.</p>
<p>This sequence confuses the framework’s validation mechanism. The framework cannot properly detect whether the previous stubbing operation was
finished or left incomplete. This breaks one of the framework’s key safety features: detecting unfinished stubbing.</p>
<p>Unfinished stubbing detection helps catch common mistakes like:</p>
<ul>
<li>Forgetting to add a return value specification after the stubbing setup</li>
<li>Putting method calls in the wrong place</li>
<li>Incomplete test setup</li>
</ul>
<p>When inline mock creation prevents this detection, you may encounter confusing error messages in <em>subsequent</em> tests rather than in the test
that contains the actual problem. This makes debugging significantly harder because the error location and the root cause are separated.</p>
<h3>What is the potential impact?</h3>
<p>When this pattern is used, the testing framework’s validation system is compromised. The immediate consequence is that developers lose the safety
net that detects incomplete or improperly configured test doubles.</p>
<p>This can lead to:</p>
<ul>
<li>Test failures appearing in the current or following tests, making debugging time-consuming</li>
<li>Misleading error messages that point to the wrong location</li>
<li>Reduced confidence in the test suite</li>
</ul>
<p>In Mockito, this pattern specifically breaks the framework’s ability to detect unfinished stubbing, which is one of its key safety features.</p>
<h2>How to fix it</h2>
<p>Extract the mock object creation to a local variable, then pass that variable to <code>thenReturn()</code>. This ensures Mockito can properly track
the stubbing sequence and validate that it is complete.</p>
<h3>Code examples</h3>
<h4>Noncompliant code example</h4>
<pre data-diff-id="1" data-diff-type="noncompliant">
import static org.mockito.Mockito.*;

class MyTest {
void testMethod() {
MyClass mock = mock(MyClass.class);
when(mock.foo()).thenReturn(mock(Foo.class)); // Noncompliant
}
}
</pre>
<h4>Compliant solution</h4>
<pre data-diff-id="1" data-diff-type="compliant">
import static org.mockito.Mockito.*;

class MyTest {
void testMethod() {
MyClass mock = mock(MyClass.class);
Foo foo = mock(Foo.class);
when(mock.foo()).thenReturn(foo);
}
}
</pre>
<h2>Resources</h2>
<h3>Documentation</h3>
<ul>
<li>Mockito Wiki - <a href="https://github.com/mockito/mockito/wiki/FAQ#can-i-thenreturn-an-inlined-mock-">FAQ - Can I thenReturn() an inlined
mock()?</a></li>
</ul>

Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"title": "Mock objects should not be created inline within \"thenReturn()\"",
"type": "CODE_SMELL",
"status": "ready",
"remediation": {
"func": "Constant\/Issue",
"constantCost": "5min"
},
"tags": [
"mockito",
"tests"
],
"defaultSeverity": "Major",
"ruleSpecification": "RSPEC-9016",
"sqKey": "S9016",
"scope": "Tests",
"quickfix": "unknown",
"code": {
"impacts": {
"MAINTAINABILITY": "MEDIUM"
},
"attribute": "CLEAR"
}
}
Empty file.
Loading