首页 > 解决方案 > 如何从 MockMultipartFile 在 Spring MVC 测试中生成异常?

问题描述

我正在尝试为 Spring MVC 中的控制器编写一些单元测试,并且部分控制器方法具有以下代码:

        try {
            newProjectFile.setFileType(fileType);
            newProjectFile.setContent(BlobProxy.generateProxy(file.getInputStream(), file.getSize()));
        } catch (Exception e) {
            throw new BadUpdateException(e.getMessage());
        }

我在我的单元测试中设置了一个 MockMultipartFile ,并想在这里测试异常情况,以便我可以获得错误的请求响应。

我尝试设置如下内容:

单元测试:

MockMultipartFile file = new MockMultipartFile("file", "receipts.zip", "application/zip", "".getBytes());

[...]

when(file.getInputStream()).thenThrow(IOException.class);

[...]

我收到以下错误:

when() requires an argument which has to be 'a method call on a mock'.
For example:
    when(mock.getArticles()).thenReturn(articles);

如果我不能像使用任何普通的模拟对象一样在 MockMultipartFile 上使用“何时”,并且 Mockito 不允许您模拟静态方法,我怎样才能在此处抛出异常?

编辑:如评论中所述,MockMultipartFile 不是来自 Mockito,因此出现上述错误。

问题实际上是如何在 try/catch 块中引发异常,这可能通过在 file.getInputStream() 上引发 IOException 或在 BlobProxy.generateProxy() 上引发 UnsupportedOperationException,以便我的方法引发 BadUpdateException。

标签: javamockingmockitospring-mvc-test

解决方案


所以我的同事找到了一个使用匿名内部类来解决这个问题的好方法:

            @Override
            public InputStream getInputStream() throws IOException {
                throw new IOException();
            }
        };

这意味着当试图从 MockMultipartFile 中获取 InputStream 时,控制器方法中的 try/catch 块中会抛出异常,结果是 BadUpdateException。


推荐阅读