unit-testingmockito

Why avoid using Mockito.verify?


My company does not allow to use Mockito.verify in Unit Test. There even is a customized sonar rule about it.
The rule is as below.
The results should be verified by assertions rather than using the verify to do process verification. Because if we verify the process, need more effort to maintain tests after the process is changed,but input and output remain the same. Make sure that every line of code has an impact on the results, and assert the results to prove the logic is correct.
Noncompliant Code Example

verify(graphics2D, times(1)).dispose();// Noncompliant

Compliant Solution

assertThat(((SunGraphics2D) graphics2D).getSurfaceData()).isInstanceOf(NullSurfaceData.class);

For database or middleware operations, assert the data was write successful using the embedded database or middleware.

For restful requests, use wiremock's verify to assert that the mock server received the corresponding request。

WireMock.verify(postRequestedFor(urlEqualTo("http://localhost:8080/query"))
                .withHeader("Content-Type", equalTo("application/json"))
                .withRequestBody(equalToJson("{" +
                        "\"testing-library\": \"WireMock\"," +
                        "\"creator\": \"Tom Akehurst\"," +
                        "\"website\": \"wiremock.org\"" +
                        "}")));

My question is, does any other IT company have similar rule to avoid using Mockito.verify in Unit Test? Is it a good rule or evil rule? Thank you very much.


Solution

  • Well, this would require a long answer, but I will try to make it short. Change company. It's basically two different kind o tests. In one case you're checking input and output (assert), in the other case your output very likely is void and then you just verify that the function is called.

    Besides that, you use verify for "integration tests" where you want to verify that the functions are called and also you may want to verify the order in which they are called with "inOrder()" as explained here: Mockito verify order / sequence of method calls

    Sometimes unit tests and integration tests overlap. There are 2 subtypes of integration tests:

    Lately a maven plugin has been used which allows to spawn docker containers at will during the test or verify phases.

    <groupId>io.fabric8</groupId>
    <artifactId>docker-maven-plugin</artifactId>
    <version>0.33.0</version>
    

    That allows you to run integration tests and end to end tests within your project in a common Jenkins pipeline. The only problem appears when you cannot use docker in Jenkins because docker is not installed on the machine that runs the tests.