3 回答

TA貢獻1820條經驗 獲得超9個贊
我在測試中遇到了同樣的問題,我想出的最佳解決方案是: Mock static method in Clock.systemUTC so it will return Clock.fixed()
try (MockedStatic<Clock> utilities = Mockito.mockStatic(Clock.class)) {
utilities.when(Clock::systemUTC)
.thenReturn(Clock.fixed(Instant.parse("2018-08-22T10:00:00Z"), ZoneOffset.UTC));
System.out.println(Instant.now()) //here perform actions in past
}
System.out.println(Instant.now()) // here perform in current time

TA貢獻1735條經驗 獲得超5個贊
就我而言,配備的屬性的數據類型@UpdateTimestamp是LocalDateTime. 我是這樣解決的:
ShiftLog shiftLog1 = ShiftLog.builder().build();
ShiftLog shiftLog2 = ShiftLog.builder().build();
ShiftLog shiftLog3 = ShiftLog.builder().build();
LocalDateTime thePast = LocalDateTime.of(1979, 4, 3, 6, 45, 31);
try (MockedStatic<LocalDateTime> utilities = Mockito.mockStatic(LocalDateTime.class)) {
utilities.when(() -> LocalDateTime.now(ArgumentMatchers.any(Clock.class))).thenReturn(thePast);
repository.save(shiftLog1);
repository.save(shiftLog2);
}
// Now the @UpdateTimestamp is untouched again.
repository.save(shiftLog3);
添加回答
舉報