rspec/rules/S6068/java/rule.adoc

50 lines
1.5 KiB
Plaintext

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
----
@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
----
@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);
}
----
== See
* 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[]
'''
== Comments And Links
(visible only on this page)
include::comments-and-links.adoc[]
endif::env-github,rspecator-view[]