【发布时间】:2021-04-06 10:30:23
【问题描述】:
我的用例是我使用 JUnit 5 并且需要模拟静态方法 YearMonth.now()。
为此,我使用的解决方案是:
YearMonth defaultYearMonth = YearMonth.of(DEFAULT_YEAR, Month.MARCH);
try (MockedStatic<YearMonth> mockedScope = Mockito.mockStatic(YearMonth.class)) {
mockedScope.when(YearMonth::now).thenReturn(defaultYearMonth);
// Rest of the code
// StepVerifier to verify a subscription
}
现在的问题是,由于在模拟范围内模拟 YearMonth,我无法模拟所有其他方法。但我想调用YearMonth.from() 的真正方法。
为此,我尝试添加
mockedScope.when(() -> YearMonth.from(any())).thenCallRealMethod();
但这不起作用,我得到了null,其中调用了YearMonth.from(LocalDateTime)。
我不确定我错过了什么。如果可能是由于模拟 YearMonth 类,有没有办法监视静态方法?如果没有任何关于如何使用 JUnit 5 实现这一点的帮助将非常有帮助。
【问题讨论】:
标签: java unit-testing junit junit5