简体   繁体   中英

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

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 eg +/- 10 seconds compared to LocalDateTime.now() .

It come from the difference in the date createdOn expected 2020-07-08T12:29:02.992775+02:00 and sended 2020-07-08T12:29:02.999827+02:00

The date instanciate in your test differ a little from the one instanciate in your code.

If you want to make complex assert on the date like 'inSameMinuteWindows' you should take a look to Captor in mockito and assertJ who provide lot of helpful assert for comparing date.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM