Mockito then() should() 匹配不包括一个参数的参数

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

我可以看到时间戳不同。我想避免比较时间戳。我尝试使用 not() 但没有成功。

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

我有这个错误

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

它来自预期的创建日期 2020-07-08T12:29:02.992775+02:00 和发送日期 2020-07-08T12:29:02.999827+02:00 的差异

您测试中实例化的日期与代码中实例化的日期略有不同。

如果你想像 'inSameMinuteWindows' 这样在日期上做复杂的断言,你应该看看 mockito 中的 Captor 和 assertJ,他们提供了很多有用的断言来比较日期。

您可以为此使用 ArgumentCaptor,并在验证调用时使用 caputre 实际方法参数。

此测试框架可能如下所示(假设您使用 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());
  }
}

在断言中,您可能想要检查时间戳是否在一个范围内,例如与 LocalDateTime.now().

相比 +/- 10 秒