@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK, classes = DemoApplication.class)
@AutoConfigureMockMvc
@TestPropertySource(locations = "classpath:application.properties")
@TestMethodOrder(OrderAnnotation.class)
public class UploadFileTest {
@Autowired
private MockMvc mockMvc;
@Disabled
@Test
public void uploadTest() throws Exception {
// new MockMultipartFile("file", "test", "application/ms-excel", new
// FileInputStream(new File("..../upload/from/flower.excel"))
// InputStream inStream =
// getClass().getClassLoader().getResourceAsStream(filename);
ContentType ct = ContentType.IMAGE_PNG;
InputStream inStream = new FileInputStream("..../upload/from/flower.png");
MockMultipartFile mfile = new MockMultipartFile("file", "flower02.png", "png", inStream);
MockHttpServletRequestBuilder mockhttp = MockMvcRequestBuilders.multipart("/upload").file(mfile)
.contentType(MediaType.IMAGE_PNG);
ResultActions resultActions = mockMvc.perform(mockhttp);
MvcResult mvcResult = resultActions.andDo(MockMvcResultHandlers.print())
.andExpect(MockMvcResultMatchers.status().isOk()).andReturn();
String result = mvcResult.getResponse().getContentAsString();
System.out.println("return msg:" + result);
}文章来源地址https://www.toymoban.com/news/detail-484397.html
@Test
public void downloadTest() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/download/build.gradle"))
.andExpect(MockMvcResultMatchers.status().isOk()).andDo(new ResultHandler() {
@Override
public void handle(MvcResult result) throws Exception {
result.getResponse().setCharacterEncoding("UTF-8");
String fileName = "..../upload/dest/build.gradle";
File file = new File(fileName);
OutputStream out = new FileOutputStream(file);
out.write(result.getResponse().getContentAsByteArray());
out.close();
Assert.assertTrue(file.exists());
}文章来源:https://www.toymoban.com/news/detail-484397.html
});
}
}
到了这里,关于mockmvc upload and download的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!