使用Spring MockMvc 测试spring mvc 生成的EXCEL

来源:互联网 发布:php如何调用静态方法 编辑:程序博客网 时间:2024/06/07 22:58

1. SPRING MVC 生成EXCEL


@RequestMapping(value = "/requestFileByJson", method = RequestMethod.POST)public void  getListByCallFunction(@RequestBody String data, HttpServletRequest request,HttpServletResponse response, HttpSession session) throws Exception {response.setContentType("application/ms-excel;charset=UTF-8");response.setHeader("Content-Disposition","attachment;filename=".concat(String.valueOf(URLEncoder.encode(systemID + "_"+JName+".xls", "UTF-8"))));OutputStream out = response.getOutputStream();String sheetName = "导出WEBEDI";String titleNames = null;resultMapList = new ArrayList();HSSFWorkbook excel = excelWordService.getExcelByDataMap(resultMapList,sheetName,titleNames);excel.write(out);                          out.flush();}

2. 使用MockMvc 进行测试生成的EXCEL

@Testpublic void testInserOneLine() throws Exception {String URI = "/Interface/requestFileByJson?JName=T_PAYMENT&JType=INTERFACE&systemID=HD_FA_PAYMENT&fileType=excel&bizUnitName=voucher_export&token=test";String requestBody = "{\"T_PAYMENT\":\"[{\\\"LINE_ID\\\":" + getUnicID()+ ",\\\"ORG_ID\\\":2094,\\\"GROUP_ID\\\":2101,\\\"PURPOSE_NAME\\\":\\\"业务成本\\\" 1,\\\"CURRENCY_CODE\\\":\\\"CNY\\\",\\\"AMOUNT\\\":21.01}, {\\\"LINE_ID\\\":"+ getUnicID()+ ",\\\"ORG_ID\\\":2094,\\\"GROUP_ID\\\":2101,\\\"PURPOSE_NAME\\\":\\\"业务成本\\\" 1,\\\"CURRENCY_CODE\\\":\\\"CNY\\\",\\\"AMOUNT\\\":55.41} ]\"}";this.mockMvc.perform(post("/Interface/requestFileByJson").param("JName", "T_FUNCTION_LIST").param("JType", "DB").contentType(MediaType.APPLICATION_JSON).content(requestBody).accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andDo(new ResultHandler() {@Overridepublic void handle(MvcResult result) throws Exception {result.getResponse().setCharacterEncoding("UTF-8");MockHttpServletResponse contentRespon = result.getResponse();InputStream contentInStream = new ByteArrayInputStream(contentRespon.getContentAsByteArray());HSSFWorkbook resultExcel = new HSSFWorkbook(contentInStream);Assert.assertEquals("application/ms-excel", contentRespon.getContentType());HSSFSheet sheet = resultExcel.getSheet("WEBEDI");Assert.assertNotNull(sheet);String filePath = "test-webedi-export.xls";File file = new File(filePath);// if(file.exists())file.delete();resultExcel.write(file);resultExcel.close();Assert.assertTrue(file.exists());}});}




原创粉丝点击