模拟 LocalDate.now() 但在使用 plusDays 时它 returns 为空?

Mocking LocalDate.now() but when using plusDays it returns null?

在我的代码中,我需要使用 LocalDate.now(),然后我使用 plusDays(num).

计算出从今天开始的估计日期

在我的单元测试中,当我模拟静态 .now() 方法时,当它调用 plusDays() 方法时输出为空。

有什么想法吗?

代码

LocalDate today = LocalDate.now();
int estimatedDays = fullPeriod - countSoFar;
LocalDate estimatedDate  = today.plusDays(estimatedDays);

测试

try(MockedStatic<LocalDate> mockedLocalDate = Mockito.mockStatic(LocalDate.class)) {
            mockedLocalDate.when(LocalDate::now).thenReturn(startDate);

            String actual = generator.generateCsv("text", "text", startDate, endDate);

            String expected = "Some text containing {Estimated Date}";
            assertEquals(expected, actual);
}

编辑:

当我模拟 LocalDate 时,它​​在对 LocalDate.now() 的调用中看起来很正常,但是当它进入 plusDay() 方法时它 returns null

此时在数学函数内部 r 不为空,但是一旦它从这个方法中出来,结果变量是?

java.time.Clock

您可以使用 Clock feature offered by the java.time API itself. You can pass an instance of java.time.Clock, a fixed 时钟,而不是模拟静态方法(在我看来,这从来都不是一个好主意)。

来自 Clock JavaDoc:

Best practice for applications is to pass a Clock into any method that requires the current instant. A dependency injection framework is one way to achieve this:

public class MyBean {
 private Clock clock;  // dependency inject
 ...
 public void process(LocalDate eventDate) {
   if (eventDate.isBefore(LocalDate.now(clock)) {
     ...
   }
 }
}   

This approach allows an alternate clock, such as fixed or offset to be used during testing.