Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate exception in Spring MVC test from MockMultipartFile?

I am trying to write some unit tests for a controller in Spring MVC, and part of the controller method has the follwing code:

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

I've set up a MockMultipartFile in my unit test, and would like to test the exception case here so that I can get a bad request response.

I've tried setting up something like the following:

unit test:

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

[...]

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

[...]

and I get the following error:

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

If I can't use 'when' on a MockMultipartFile like I would any normal mock object, and Mockito doesn't allow you to mock static methods, how can I get an exception to be thrown here?

Edit: as mentioned in the commments, the MockMultipartFile is not from Mockito, hence the error mentioned above.

The question really is how to throw an exception in the try/catch block, which is presumably either by throwing an IOException on file.getInputStream(), or an UnsupportedOperationException on BlobProxy.generateProxy(), so that my method throws the BadUpdateException.

like image 484
M Hall Avatar asked Sep 16 '25 06:09

M Hall


1 Answers

So my colleague found a good way to get around this using an anonymous inner class:

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

This means that an exception is thrown in the try/catch block in the controller method when trying to get the InputStream from the MockMultipartFile, and the result is the BadUpdateException.

like image 115
M Hall Avatar answered Sep 19 '25 14:09

M Hall