@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);
}
@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());
}
});
}
}