0

If I want to verify either that no errors or some errors have been logged, but there are multiple error logging methods, I could do something clumsy like this:

Logger log = mock(Logger.class);
boolean errorsExpected;
...
if (errorsExpected) {
    try {
        verify(log, atLeastOnce()).error(any());
    } catch (AssertionError e) {
        verify(log, atLeastOnce()).error(any(), any());
    }
} else {
    verify(log, never()).error(any());
    verify(log, never()).error(any(), any());
}

Is there a better way?

H.v.M.
  • 1,348
  • 3
  • 16
  • 42

1 Answers1

0

This isn't something Mockito excels at, but unless you need any of the clever Mockito matcher functionality to match errors, you can just write a fake Logger youself.

To do this, implement Logger—manually using Java or dynamically using Mockito thenAnswers—and have each call increment a counter or save its arguments to an array. At the end of the test you could check error count or make any other queries you need.

If multiple tested components call your Logger, you can write the fake implementation once and use it for all the querying you need in all your unit and small integration tests.

This is similar to what the Android testing library Robolectric does with its ShadowLog.getLogs implementation, though Robolectric uses a custom classloader to replace the Log class due to its static methods.

Jeff Bowman
  • 90,959
  • 16
  • 217
  • 251