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();
}
}
You can get a byte array from MvcResult .getResponse().getContentAsByteArray()
.
From there you can convert a ByteArrayInputStream
into a File
or ZipFile
for comparison.
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());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With