对于文件上传的单测如下:
@RunWith(PandoraBootRunner.class)
@SpringBootTest(classes = {Application.class})
@DelegateTo(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
public class OssControllerTest {
@Autowired
private WebApplicationContext context;
private MockMvc mockMvc;
private final String PRE_OSS_UPLOAD_URI = "/api/oss";
private final String UPLOAD_PICTURE = "Picture";
private final String UPLOAD_TEXT = "txt";
private final String UPLOAD_PICTURE_ADDRESS = "C:\\Windows\\Web\\Wallpaper\\Windows\\img0.jpg";
private final String UPLOAD_TEXT_ADDRESS = "C:\\Windows\\PLA\\System\\System Diagnostics.xml";
private final String PICTURE_ORIGINAL_FILENAME = "img0.jpg";
private final String TEXT_ORIGINAL_FILENAME = "System Diagnostics.xml";
@Before
public void before() throws Exception {
mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
}
/**
* /api/oss/uploadFile 正常情况
* @throws Exception
*/
@Test
public void uploadFile() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.post(PRE_OSS_UPLOAD_URI + "/uploadFile"))
.andExpect(MockMvcResultMatchers.status().isOk());
}
/**
* /api/oss/uploadFile 上传一个小于5M的图片
* @throws Exception
*/
@Test
public void uploadFileResultPictureVerify() throws Exception {
uploadFileResultVerify(UPLOAD_PICTURE);
}
/**
* /api/oss/uploadFile 上传一个小于5M的文本
* @throws Exception
*/
@Test
public void uploadFileResultTxtVerify() throws Exception {
uploadFileResultVerify(UPLOAD_TEXT);
}
/**
* 测试文件上传核心逻辑
* @param flag
* @throws Exception
*/
private void uploadFileResultVerify(String flag) throws Exception {
MockMultipartFile firstFile = null;
if (flag.equalsIgnoreCase(UPLOAD_PICTURE)){
File file = new File(UPLOAD_PICTURE_ADDRESS);
firstFile = new MockMultipartFile("file", PICTURE_ORIGINAL_FILENAME, MediaType.TEXT_PLAIN_VALUE, new FileInputStream(file));
}else if (flag.equalsIgnoreCase(UPLOAD_TEXT)){
File file = new File(UPLOAD_TEXT_ADDRESS);
firstFile = new MockMultipartFile("file", TEXT_ORIGINAL_FILENAME, MediaType.TEXT_PLAIN_VALUE, new FileInputStream(file));
}
ResultActions perform = mockMvc.perform(MockMvcRequestBuilders
.fileUpload(PRE_OSS_UPLOAD_URI + "/uploadFile").file(firstFile));
String contentAsString = perform.andDo(print()).andReturn().getResponse().getContentAsString();
Assert.assertNotNull(contentAsString);
}
}