Search code examples
javamockitospring-boot-test

Mockito then() should() match arguments excluding one argument


I'm able to see there is difference in the timestamp. I want to avoid comparing timestamps. I try using not() but no luck.

OffsetDateTime offsetDateTime = OffsetDateTime.now();

RequestInfo requestInfo = new RequestInfo();
requestInfo.setDeviceId("mobile11");
requestInfo.setToken("1234567");

service.updateDeviceInformation(requestInfo);
 
then(repo).should().mergeRequestInformation(defaultEntryBuilder(offsetDateTime).build());

RequestInformationRepository.java
private final EntityManager entityManager;
public RequestInformation mergeRequestInformation(RequestInformation requestInformation) {
        return entityManager.merge(requestInformation);
    }

I having this error

Error: Argument(s) are different! Wanted:
se.repository.RequestInformationRepository#0
bean.mergeRequestInformation(
    RequestInformation(token=1234567, deviceId=mobile11, createdOn=2020-07-08T12:29:02.992775+02:00) ); 
-> at se.service.RegisterServiceTest.shouldStoreRegisterEntryInRepository(ServiceTest.java:43)
Actual invocations have different arguments:
se.repository.RequestInformationRepository#0
bean.mergeDeviceInformation( RequestInformation(token=1234567, deviceId=mobile11, createdOn=2020-07-08T12:29:02.999827+02:00) );

Solution

  • You can use an ArgumentCaptor for this and caputre the actual method argument when verifying the invocation.

    A test skeleton for this might look like the following (assuming you use JUnit 5):

    @ExtendWith(MockitoExtension.class)
    public class YourTest {
    
      @Mock
      private RequestInformationRepository repo;
    
      @Captor
      private ArgumentCaptor<RequestInformation> requestInformationArgumentCaptor;
    
      @Test
      public void test() {
        
        // ... your setup
    
        then(repo).should().mergeRequestInformation(requestInformationArgumentCaptor.capture());
    
        assertEquals(LocalDateTime.now().getHour(), uriArgumentCaptor.getValue()..getCreatedOn().getHour());
      }
    }
    

    In the assertion, you might want to check that the timestamp is between a range of e.g. +/- 10 seconds compared to LocalDateTime.now().