当存根看起来像文档时,为什么我在Mockito中获得UnifnishedStubException?

时间:2018-02-19 19:35:45

标签: java testing mockito tdd stub

我使用Mockito框架获得以下测试文件:

    @Rule
    public ExpectedException expectedException = ExpectedException.none();

    @Spy    
    private JarExtracter jExt = Mockito.spy(JarExtracter.class);

    @Test
    public void inputStreamTest() throws IOException {
        String path = "/edk.dll";       

        // Call the method and do the checks                    
        jExt.extract(path);                 

        // Check for error with a null stream
        path = "/../edk.dll";       
        doThrow(IOException.class).when(jExt).extract(path);   
        jExt.extract(path);

        verifyNoMoreInteractions(jExt);        
        expectedException.expect(IOException.class);
        expectedException.expectMessage("Cannot get");

doThrow()行返回:

org.mockito.exceptions.misusing.UnfinishedStubbingException: 
Unfinished stubbing detected here:
-> at confusionIndicator.tests.JarExtracterTests.inputStreamTest(JarExtracterTests.java:30)

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();
Hints:
 1. missing thenReturn()
 2. you are trying to stub a final method, you naughty developer!
 3: you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed

我尝试了不同的方法来测试此错误抛出行为,但我无法摆脱这个错误消息,这使我的测试失败。任何帮助将非常感谢!

1 个答案:

答案 0 :(得分:1)

使用您编写的代码,我在JarExtractor的以下存根中添加了代码,并且代码运行正常,给出了您期望的IOException:

class JarExtracter {
    public void extract(String path) throws IOException{

    }
}

用以下内容替换它,我得到了与你相同的UnfinishedStubbingException:

class JarExtracter {
    final public void extract(String path) throws IOException{

    }
}

---编辑---同样,如果方法是静态的:

class JarExtracter {
    public static void extract(String path) throws IOException{

    }
}

正如您在评论中所说,您的方法是静态的,因此您将无法使用Mockito进行模拟。 以下是关于前进方向的一些好建议for dealing with final methods,以及mocking static methods上的一些建议。