Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I test a spring controller that returns a zip file?

I have a controller that returns a ZIP file. I would like to compare the ZIP file with the expected ZIP, but I'm not sure how to get the file from my result.

Here is what I have so far:

public class FileControllerTest extends ControllerTest {

  @InjectMocks
  private FileController controller;

  @Autowired
  private WebApplicationContext context;

  private MockMvc mvc;

  @Before
  public void initTests() throws IOException {
    MockitoAnnotations.initMocks(this);
    mvc = MockMvcBuilders.webAppContextSetup(context).build();
  }

  @Test
  public void shouldReturnZip() throws Exception {
    MvcResult result = mvc
        .perform(get(SERVER + FileController.REQUEST_MAPPING + "/zip").accept("application/zip"))
        .andExpect(status().isOk()).andExpect(content().contentType("application/zip"))
        .andDo(MockMvcResultHandlers.print()).andReturn();

  }
}
like image 836
Ann Addicks Avatar asked Sep 10 '15 14:09

Ann Addicks


2 Answers

You can get a byte array from MvcResult .getResponse().getContentAsByteArray(). From there you can convert a ByteArrayInputStream into a File or ZipFile for comparison.

like image 190
Jerry Bartone Avatar answered Nov 15 '22 09:11

Jerry Bartone


    final byte[] contentAsByteArray = mvc.perform(get("/zip-xlsx")
            .header(CORRELATION_ID_HEADER_NAME, CID))
            .andDo(print())
            .andExpect(status().isOk())
            .andReturn().getResponse().getContentAsByteArray();
    
    try (final var zin = new ZipInputStream(new ByteArrayInputStream(contentAsByteArray))) {
        ZipEntry entry;
        String name;
        long size;

        while ((entry = zin.getNextEntry()) != null) {

            name = entry.getName();
            size = entry.getSize();

            System.out.println("File name: " + name + ". File size: " + size);

            final var fout = new FileOutputStream(name);
            for (var c = zin.read(); c != -1; c = zin.read()) {
                fout.write(c);
            }
            fout.flush();
            zin.closeEntry();
            fout.close();
        }

    } catch (Exception ex) {
        System.out.println(ex.getMessage());
    }
like image 44
makson Avatar answered Nov 15 '22 09:11

makson