rspec/rules/S6068/java/rule.adoc

75 lines
2.1 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
2021-04-28 16:49:39 +02:00
Mockito provides _argument matchers_ for flexibly stubbing or verifying method calls.
``++Mockito.verify()++``, ``++Mockito.when()++``, ``++Stubber.when()++`` and ``++BDDMockito.given()++`` each have overloads with and without argument matchers.
However, the default matching behavior (i.e. without argument matchers) uses ``++equals()++``. If only the matcher ``++org.mockito.ArgumentMatchers.eq()++`` is used, the call is equivalent to the call without matchers, i.e. the ``++eq()++`` is not necessary and can be omitted. The resulting code is shorter and easier to read.
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
@Test
public void myTest() {
given(foo.bar(eq(v1), eq(v2), eq(v3))).willReturn(null); // Noncompliant
when(foo.baz(eq(v4), eq(v5))).thenReturn("foo"); // Noncompliant
doThrow(new RuntimeException()).when(foo).quux(eq(42)); // Noncompliant
verify(foo).bar(eq(v1), eq(v2), eq(v3)); // Noncompliant
}
----
=== Compliant solution
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
@Test
public void myTest() {
given(foo.bar(v1, v2, v3)).willReturn(null);
when(foo.baz(v4, v5)).thenReturn("foo");
doThrow(new RuntimeException()).when(foo).quux(42);
verify(foo).bar(v1, v2, v3);
}
----
== Resources
2021-04-28 16:49:39 +02:00
* https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#argument_matchers[Mockito documentation] - argument matchers
* S6073 - Mockito argument matchers should be used on all parameters
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Remove this/these useless "eq" invocation and directly use the value
=== Highlighting
primary: first "eq()"
secondary: other subsequent "eq()" in the rest of the method invocation
'''
== Comments And Links
(visible only on this page)
=== is related to: S6073
=== on 6 Nov 2020, 17:07:19 Michael Gumowski wrote:
Rule idea contributed by Björn Duderstadt, in the community: \https://community.sonarsource.com/t/java-call-to-mockito-method-verify-when-or-given-can-be-simplified/33974
endif::env-github,rspecator-view[]