rspec/rules/S6073/java/rule.adoc

67 lines
2.0 KiB
Plaintext
Raw Normal View History

2021-04-28 16:49:39 +02:00
Mockito provides _argument matchers_ and _argument captors_ 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, if argument matchers or captors are used only on some of the parameters, all the parameters need to have matchers as well, otherwise an ``++InvalidUseOfMatchersException++`` will be thrown.
This rule consequently raises an issue every time matchers are not used on all the parameters of a stubbed/verified method.
2021-04-28 16:49:39 +02:00
== Noncompliant Code Example
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(anyInt(), i1, i2)).willReturn(null); // Noncompliant
when(foo.baz(eq(val1), val2)).thenReturn("hi"); // Noncompliant
doThrow(new RuntimeException()).when(foo).quux(intThat(x -> x >= 42), -1); // Noncompliant
verify(foo).bar(i1, anyInt(), i2); // Noncompliant
ArgumentCaptor<Integer> captor = ArgumentCaptor.forClass(Integer.class);
verify(foo).bar(captor.capture(), i1, any()); // Noncompliant
}
----
2021-04-28 16:49:39 +02:00
== Compliant Solution
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(anyInt(), eq(i1), eq(i2))).willReturn(null);
when(foo.baz(val1, val2)).thenReturn("hi");
doThrow(new RuntimeException()).when(foo).quux(intThat(x -> x >= 42), eq(-1));
verify(foo).bar(eq(i1), anyInt(), eq(i2));
ArgumentCaptor<Integer> captor = ArgumentCaptor.forClass(Integer.class);
verify(foo).bar(captor.capture(), any(), any());
}
----
2021-04-28 16:49:39 +02:00
== See
* https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#argument_matchers[Mockito documentation] - argument matchers
* S6068 - Call to Mockito method "verify", "when" or "given" should be simplified
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::message.adoc[]
include::highlighting.adoc[]
'''
== Comments And Links
(visible only on this page)
include::comments-and-links.adoc[]
endif::env-github,rspecator-view[]