我一直在使用 JUnit 5 和 Mockito 对我将向您展示的以下代码进行单元测试,但它无法正常工作。我要评估成功案例
public Maybe < MyResponse> generate(String numberValue) {
return Maybe.just(numberValue)
.filter(number -> number.length() == Constants.REQUEST_REQUIRED) //R_R = 16
.flatMap(number -> MyUtils.generate())
.map(MyMapper::createResponse)
.switchIfEmpty(Maybe.error(MyExceptioManager.throwException400(...)));
}
我尝试将静态方法转换为实例方法,然后使用@Mock 调用它们,但没有用。我该怎么做?
我这样做了:
@Test
void generate() {
String numberValue = "1234567891234567";
// when(myUtils.generate()).thenReturn(any());
when(numberValue.length()).thenReturn(eq(16));
when(myMapper.createResponse(anyString())).thenReturn(any(MyResponse.class));
myService.generate(numberValue )
.test()
.assertNoErrors()
.assertComplete()
.assertValue(myResponse -> myResponse.getCode().equals("1234"));
}
错误:
org.mockito.exceptions.misusing.MissingMethodInvocationException: when() 需要一个参数,该参数必须是“对模拟的方法调用”。 例如: 当(mock.getArticles()).thenReturn(文章);
您可以通过以下代码在静态类中模拟静态方法:
...
try (MockedStatic<MyUtils> utilities = Mockito.mockStatic(MyUtils.class)) {
utilities.when(MyUtils::generate).thenReturn(...what your method should return...);
//test your target method like:
myService.generate(numberValue);
}