Search code examples
springziphttpresponse

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();

  }
}

Solution

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