簡體   English   中英

Mockito then() should() 匹配 arguments 不包括一個參數

[英]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) );

您可以為此使用ArgumentCaptor並在驗證調用時捕獲實際的方法參數。

對此的測試框架可能如下所示(假設您使用 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 秒的范圍內。

它來自於預計 2020-07-08T12:29:02.992775+02:00 和發送 2020-07-08T12:29:02.999827+02:00 的日期差異

測試中實例化的日期與代碼中實例化的日期略有不同。

如果您想在“inSameMinuteWindows”之類的日期上進行復雜的斷言,您應該查看 mockito 中的 Captor 和 assertJ,他們提供了很多有用的斷言來比較日期。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM