如何解决模拟静态无效方法时抛出“UnfinishedStubingException:此处检测到未完成的存根”
运行以下代码时,我在此处收到错误消息 Unfinished Stubbing detection:
这是带有 public static void myMethod 的 MyClass。
class MyClass{
public static void myMethod(){
return;
}
}
这是带有 myMethod2 方法的 MyClass2。在 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");
}
}
运行此方法时,我收到 UnfinishedStubingException。
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.
解决方法
我相信 https://www.baeldung.com/mockito-mock-static-methods 给出了很好的解释。看着这一点,我认为以下内容应该可行:
class MyMethodTest{
MyClass2 myClass2;
@Test
public void myMethodTwoTest(){
PowerMockito.mockStatic(MyClass.class).when(MyClass::myMethod).doNothing();
String str = myClass2.myMethod2();
assertEquals(str,"String");
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。