java - 在方法内部调用方法时模拟异常

标签 java testing junit mockito

我有这段代码,我想在调用 try block 内的 close 方法时用mockito抛出 IOException

public static void cleanup(Logger log, Closeable... closeables) {
        for (Closeable c : closeables) {
            if (c != null) {
                try {
                    c.close();
                } catch (IOException e) {
                    if (log != null) {
                        log.warn("Exception in closing " + c, e);
                    }
                }
            }
        }
    }

这是我在测试方法中尝试过的,但显然它不起作用:

OutputStream outputStream = Mockito.mock(OutputStream.class);
doThrow(new IOException()).when(outputStream).close();

cleanup(log, closeables);

我怎样才能实现我的目标?谢谢!

最佳答案

您需要确保将模拟作为第二个参数传递给cleanup方法。

以下测试对我有用:

    @Test
    public void testException() throws IOException {
        OutputStream outputStream = Mockito.mock(OutputStream.class);
        doThrow(new IOException()).when(outputStream).close();
        cleanup(log, outputStream);

        Mockito.verify(outputStream, times(1)).close(); // make sure #close method is called once
    }

cleanup 方法看起来是正确的。无需更改。

关于java - 在方法内部调用方法时模拟异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65130020/

相关文章:

html - 如何在 HTML 页面中查找组件的属性值而不是检查它

java - Struts Action 代理 : how to set a method?

java - 如何处理有状态的 OSGi 服务以跨包更新维护 session 状态?

java - iterator.next() 返回替代对象

ruby-on-rails - 为什么这个 Rails Controller 测试失败了?

ruby-on-rails - Rspec::允许每个实例接收消息

java - 在服务器上运行单元测试(JAX-RS)

java - 通过检查 junit 报告导致 ant 构建失败?

java - 油漆成分问题

java - 为什么 Spring Pageable 返回意外结果?