Junit 测试文件上传
2021-05-22 23:30
标签:mockmultiparthttpservletrequest 测试文件上传 文件上传,如何进行单元测试吶?从网上找了半天没找到一个可行的方法, 经过我自己的琢磨,找到了一个方法。 现分享下, 欢迎留言评论。 我的Controller 是基于 HttpServletRequest request, HttpServletResponse response 作为方法的入参数; 大致如下 public ImportCampaignCustGroupResponse importCustGroup( HttpServletRequest request, HttpServletResponse response) throws Exception { return campaignCustGroupService.importExcelFile(request, response); } 单元测试代码如下 ; 注意必须在 创建MockMultipartHttpServletRequest 对象时,把WebApplicationContext 对象绑定到MockMultipartHttpServletRequest 实例上,否则在执行
request.getServletContext() .getRealPath 这行代码时 会抛异常。 @RunWith(SpringRunner.class) @SpringBootTest @ComponentScan(basePackageClasses = MktCampaignCustGroupControllerTest.class) @WebAppConfiguration public class MktCampaignCustGroupControllerTest { @Autowired MktCampaignCustGroupController mktCampaignCustGroupController; @Autowired private WebApplicationContext wac; @Test public void testImportCustGroupTest() throws Exception { InputStream inStream = MktCampaignCustGroupControllerTest.class.getResourceAsStream("index.txt"); byte[] contentInvalid = new byte[inStream.available()]; while(inStream.read(contentInvalid) != -1) { } MockMultipartHttpServletRequest request1 = new MockMultipartHttpServletRequest(this.wac.getServletContext()); request1.setParameter("custGroupId", custGroupId); request1.setParameter("companyId", COMPANY.DM); request1.setMethod("POST"); request1.setContentType("multipart/form-data"); request1.addFile(new MockMultipartFile("custName", "\\index.txt", "text/plain", contentInvalid) ); result = mktCampaignCustGroupController.importCustGroup(request1, response); Assert.assertNotNull(result); Assert.assertEquals(IResultCode.ILLEGAL_PARAMS, result.getResult().getResultCode()); Assert.assertEquals("不支持导入非Excel文件", result.getResult().getResultMessage()); System.out.println(result); } } 本文出自 “一代宗师” 博客,请务必保留此出处http://765682.blog.51cto.com/755682/1973843 Junit 测试文件上传 标签:mockmultiparthttpservletrequest 测试文件上传 原文地址:http://765682.blog.51cto.com/755682/1973843