我有这个功能,我想添加测试,但不知道如何填写HttpServletRequest
和HttpServletResponse
部分。
public void convertXlsToPdf(HttpServletDtoRequest httpServletDtoRequest) throws Exception {
HttpServletRequest request = httpServletDtoRequest.getRequest();
HttpServletResponse response = httpServletDtoRequest.getResponse();
byte[] result =
documentService.convertBinaryExcelToPdf(IOUtils.toByteArray(request.getInputStream()));
ServletOutputStream servletOutputStream = response.getOutputStream();
response.setContentType("application/pdf");
response.setHeader("Content-Disposition",
"attachment; filename=fpdf" + System.currentTimeMillis() + ".pdf");
response.setContentLength(result.length);
servletOutputStream.write(result, 0, result.length);
servletOutputStream.flush();
servletOutputStream.close();
}
我尝试了类似的事情,但它失败并返回了IllegalStateException
。
@Test
public void convertXlsToPdf_Test() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
HttpServletDtoRequest httpServletDtoRequest = new HttpServletDtoRequest();
httpServletDtoRequest.setRequest(request);
httpServletDtoRequest.setResponse(response);
Gson gson = new GsonBuilder().create(); //--> ERROR HERE
String json = gson.toJson(httpServletDtoRequest);
this.mockMvc.perform(
MockMvcRequestBuilders.get("PATH_TO_CLIENT")
.accept(MediaType.APPLICATION_JSON).contentType(MediaType.APPLICATION_JSON)
.content(json)).andExpect(status().isOk());
verify(this.service).convertBinaryExcelToPdf(
IOUtils.toByteArray(httpServletDtoRequest.getRequest().getInputStream()));
}
例外是:
引起:com.g
oogle.gson.CircularReferenceException: circular reference error
at com.google.gson.JsonSerializationVisitor.start(JsonSerializationVisitor.java:61)
at com.google.gson.JsonSerializationVisitor.findAndInvokeCustomSerializer(JsonSerializationVisitor.java:182)
at com.google.gson.JsonSerializationVisitor.visitFieldUsingCustomHandler(JsonSerializationVisitor.java:204)
... 72 more
怎么做?感谢。