使用Spring MockMvc 測試spring mvc 生成的EXCEL

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

@Test
	public 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() {
							@Override
							public 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());

							}
						});

		}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章