簡體   English   中英

Mocking ZonedDateTime Java8

[英]Mocking ZonedDateTime Java8

我有一個 model 構造函數,它生成一個時間戳為this.timestamp = null == timestamp? ZonedDateTime.now().toInstant().toEpochMilli(): timestamp; this.timestamp = null == timestamp? ZonedDateTime.now().toInstant().toEpochMilli(): timestamp;

如何模擬 ZonedDateTime? 我需要使用測試用例驗證時間戳的值是當前時間(以毫秒為單位)。

由於它是 model,因此無法在構造函數中注入單獨clock class 的依賴項,我不希望更改源代碼。

這取決於您的 class 以及您想要做什么:

  1. 如果要模擬 class 的所有屬性,並且 class 不是最終的,則使用 mocking 框架,例如Z4D11432CA816EACB373333

     MyClass mocked = Mockito.mock(MyClass.class); Mockito.when(mocked.getTimestamp()).thenReturn(**/ your value **/ )
  2. 如果您的 class 是最終的,您只想模擬這個單一的屬性,或者屬性是最終的:

您可以創建一個 static 工廠,為您提供Instant ,然后在您的測試中替換工廠。

 class TimeFactory {

  private static Supplier<Instant>  INSTANT_SUPPLIER = Instant::now;
  public static Instant getInstant(){ return INSTANT_SUPPLIER.get(); }
  public static void setInstantSupplier(Supplier<Instant> new){ INSTANT_SUPPLIER= supplier; } 
} 

在你的構造函數中:

this.timestamp = null == timestamp ? TimeFactory.getInstant().toEpochMilli() : timestamp;

現在在您的測試中,您可以使用 setter 方法:

 TimeFactory.setInstantSupplier(()-> /*Your value*/ )
 // create your object

只需記住在測試后返回默認供應商:

TimeFactory.setInstantSupplier(Instant::now);
  1. 如果您的屬性不是最終的,那么添加一個 package 設置器,可以在您的測試中使用。

  2. 下一個解決方案(雖然不推薦)是使用反射 但這不是 mocking,這是使用強制設置私有(事件最終)屬性。

  3. 還有一種方法可以覆蓋測試時鍾

暫無
暫無

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

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