【问题标题】:Mockito then() should() match arguments excluding one argumentMockito then() should() 匹配不包括一个参数的参数
【发布时间】:2020-07-08 10:55:32
【问题描述】:

我可以看到时间戳有所不同。我想避免比较时间戳。我尝试使用 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) );

【问题讨论】:

  • 您应该添加有关 mergeRequestInformation 的信息。这个方法的参数的类型是什么?
  • 虽然它直接存储库调用。有问题添加。
  • 将时间视为依赖项 - 您的单元测试不应与挂钟时间耦合,注入一个提供时间的协作者,以便您可以用测试替身替换它。

标签: java mockito spring-boot-test


【解决方案1】:

您可以为此使用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 秒。

【讨论】:

  • 完美。您能否将其标记为解决方案,以便进一步的开发人员快速识别它?
【解决方案2】:

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

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

如果您想在日期上进行复杂的断言,例如“inSameMinuteWindows”,您应该看看 Captor in mockito 和 assertJ,他们提供了很多有用的断言来比较日期。

【讨论】:

    猜你喜欢
    • 2011-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-13
    • 1970-01-01
    • 2012-09-23
    • 2014-05-21
    • 2013-05-03
    相关资源
    最近更新 更多