Mocking Sftp class skip method call

帅比萌擦擦* 提交于 2019-12-06 16:02:11

The main problem with using mockito here is that your connect() method depends on new JSch(). Mockito is not able to mock constructor calls. But you can change that with a little workaround, as suggested in Michael Feathers book. Just extract your new JSch() to the package private getter method

private void connect() throws JSchException {
    ...
    JSch jsch = getJSch();
    ...
}

JSch getJSch() {
    return new JSch();
}

Now in your test, you can override this method to return a mocked instance

private JSch jSch = mock(JSch.class);
private SFTP sftp = new SFTP(){
    @Override
    JSch getJSch() {
        return jSch;
    }
};

It's not the most elegant solution but it's the solution worth to consider. Especially if you don't want to do a lot of refactoring.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!