javamockingmockitoassertj

How can I verify method invocations using the equivalent of AssertJ's usingRecursiveComparison


In tests, to verify data objects that do not have hashcode/equals methods, AssertJ has a very nice API:

Assertions.assertThat(result)
    .usingRecursiveComparison()
    .ignoringFields("id")
    .isEqualTo(expected)

For checking that methods have been called, I've always used Mockito:

Mockito.verify(mock, times(2)).method(eq(arg1), eq(arg2));

The situation I'm in now, I want to combine these approaches and use verify, but compare arguments using AssertJ's usingRecursiveComparison, something along these lines:

Mockito.verify(mock, times(2)).method(usingRecursiveComparison(arg1));

Is there any way to achieve this using Mockito + AssertJ, or a different library that does provide this type of API?


Solution

  • Depending on your use case, ArgumentMatchers.refEq might help:

    verify(mock, times(2)).method(refEq(arg1, "id"));
    

    or you can leverage AssertJ via ArgumentMatchers.assertArg

    verify(mock, times(2)).method(assertArg(arg -> {
        assertThat(arg)
          .usingRecursiveComparison()
          .ignoringFields("id")
          .isEqualTo(arg1)
    }));