模拟静态void方法时抛出了java“UnfinishedStubingException:此处检测到未完成的存根”
运行以下代码时,我在此处检测到错误消息Unfinished stubing:
这是带有公共静态void myMethod的MyClass
class MyClass{
public static void myMethod(){
return;
}
}
这是MyClass2和myMethod2方法。在myMethod2内部,myMethod正在调用
class MyClass2{
public String myMethod2(){
MyClass.myMethod();
return "String";
}
}
这里是为测试myMethod2而编写的测试用例
class MyMethodTest{
MyClass2 myClass2;
@Test
public void myMethodTwoTest(){
PowerMockito.mockStatic(MyClass.class);
PowerMockito.doNothing().when(MyClass.class);
MyClass.myMethod();
String str = myClass2.myMethod2();
assertEquals(str,"String");
}
}
运行此方法时,我得到UnfinishedStubbingException
org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here:
-> at **.***.***.**.MyMethodTest.myMethodTwoTest(MyMethodTest.java:125)
E.g. thenReturn() may be missing.
Examples of correct stubbing:
when(mock.isOk()).thenReturn(true);
when(mock.isOk()).thenThrow(exception);
doThrow(exception).when(mock).someVoidMethod();```
Please help me to solve this issue.
# 1 楼答案
我认为https://www.baeldung.com/mockito-mock-static-methods给出了一个很好的解释。考虑到这一点,我认为以下类似的方法应该可以奏效: