I am trying to test the following class:
Class UserSynchronizer(){
private static org.apache.log4j.Logger log = ... ;
public Sync(candidate) {
...
if (candidate.inValidForSync()) {
log.debug("Candidate #" + candidate.getId() + ": Not syncing");
}
else {
log.debug("Syncing");
}
}
}
I want to see if mockito can detect what arguments log.debug
was called with and then I want to see if I can do some kind of regex check on it. In other words, I want to:
The code below is what I have as a starting point:
public void verifySyncDoesntSyncWhenInvalid(){
//Setup candidate mock
Candidate invalidSyncCandidateMock = mock(Candidate.class);
when(invalidSyncCandidateMock.inValidForSync()).thenReturn(true);
//Setup log mock
UserSynchronizer userSynchronizer = ...;
Field logField = userSynchronizer.getClass().getDeclaredField("log");
logField.setAccessible(true);
logField.set(userSynchronizer, logMock);
//Call sync
userSynchronizer.sync(invalidSyncCandidateMock);
//Verify that debug was called with ("Candidate #\d+: Not syncing")
???
}
The problem is that log.debug
is called multiple times. I want to capture the arguments that are provided to log.debug
and ensure that when it is called with the candidate that is invalid for sync, then the logger object correctly logs that the candidate was not synced.
Edit: If this has been asked before, I apologize. I kindly ask that you post a link to the related question :)
Mockito provides regex matcher in standard org.mockito.Matchers class. Here is an example how this function can be used to verify invocation with proper parameter value:
verify(restMock, times(1)).exchange(matches(".*text=welcome.*to.*blah"), eq(HttpMethod.GET), any(ResponseEntity.class), eq(String.class));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With