有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

模拟静态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) 个答案

  1. # 1 楼答案

    我认为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");
    }