JUnit 5 模拟 YearMonth.now 但为 YearMonth.from 调用真正的方法
JUnit 5 mock YearMonth.now but call real method for YearMonth.from
我的用例是我正在使用 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
class,是否有办法监视静态方法?如果没有关于如何使用 JUnit 5 实现此目的的任何帮助,将非常有帮助。
如果您查看 Mockito.mockStatic(Class<T>)
的 Javadoc,您会发现所有静态方法都是模拟的,这意味着如果它们在你的测试。
Creates a thread-local mock controller for all static methods of the given class or interface. [...]
根据 Javadoc,修复它的方法是在 mockStatic
方法中使用一个额外的参数。第二个参数是 defaultAnswer
defaultAnswer – the default answer when invoking static methods.
MockedStatic<YearMonth> mockedScope = Mockito.mockStatic(YearMonth.class, Mockito.CALLS_REAL_METHODS)
我的用例是我正在使用 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
class,是否有办法监视静态方法?如果没有关于如何使用 JUnit 5 实现此目的的任何帮助,将非常有帮助。
如果您查看 Mockito.mockStatic(Class<T>)
的 Javadoc,您会发现所有静态方法都是模拟的,这意味着如果它们在你的测试。
Creates a thread-local mock controller for all static methods of the given class or interface. [...]
根据 Javadoc,修复它的方法是在 mockStatic
方法中使用一个额外的参数。第二个参数是 defaultAnswer
defaultAnswer – the default answer when invoking static methods.
MockedStatic<YearMonth> mockedScope = Mockito.mockStatic(YearMonth.class, Mockito.CALLS_REAL_METHODS)