Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito verify that method is called with correct argument using regex

Description

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:

  • capture the arguments provided to the log object (which I am mocking in my test atm)
  • check (using regex) if it matches a pattern like "Candidate #\d+: Not syncing" for the cases where my mock candidate object is returning false

Test code

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")
  ???
}

Problem

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 :)

like image 974
Arnab Datta Avatar asked Jan 20 '15 11:01

Arnab Datta


1 Answers

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));
like image 121
qza Avatar answered Dec 10 '22 01:12

qza