如何编写Mockito测试用例以上传文件,如下所示


@RestController
@ComponentScan
public class FileUploadController {
    @Autowired
    Environment env;
    private static final Logger logger = LoggerFactory
            .getLogger(FileUploadController.class);
    /**
     * Upload single file using Spring Controller
     */
    @RequestMapping(value = "/{name}", method = RequestMethod.POST)
    public String fileUpload(@RequestParam("file") MultipartFile file,
            @PathVariable("name") String name) throws Exception {
        System.out.println(file);
        System.out.println(name);
        if (!file.isEmpty()) {
            try {
                byte[] bytes = file.getBytes();
                // Creating the directory to store file
                Path path = Paths.get(env.getProperty("upload.dir.location"));
                // Create the file on server
                File serverFile = new File(path + "/" +name);
                BufferedOutputStream stream = new BufferedOutputStream(
                        new FileOutputStream(serverFile));
                stream.write(bytes);
                stream.close();
                logger.info("Server File Location="
                        + serverFile.getAbsolutePath());
                return "You successfully uploaded file=" + name;
            } catch (Exception e) {
                return "You failed to upload " + name + " => " + e.getMessage();
            }
        } else {
            return "You failed to upload " + name
                    + " because the file was empty.";
        }
    }
}

这是我的 application.properties 文件

server.port=8082
spring.http.multipart.max-file-size=10MB
spring.http.multipart.max-request-size=10MB
upload.dir.location=/home/user/Desktop/UploadedFiles/

我需要一个Junit或Mockito(最好是)测试案例来测试此代码。我尝试了几种格式,但到目前为止还没有找到完美的格式。有人可以建议我编写上传文件的单位测试用例吗?预先感谢!

edit-1

这是我的测试课:

@WebAppConfiguration
public class RestapiFileUploadControllerTest extends RestapiFileuploadApplicationTests{
    private MockMvc mvc;
    @Autowired
    private WebApplicationContext webApplicationContext;
    @Autowired
Environment env;
@Test
public void testUploadedFile() throws Exception{
    File f = new File("/home/user/Documents/response.pdf");
    System.out.println(f.isFile()+"  "+f.getName()+"  "+f.exists());
    FileInputStream fi1 = new FileInputStream(f);
    FileInputStream fi2 = new FileInputStream(new File("/home/user/Desktop/UploadedFiles/response"));
    MockMultipartFile fstmp = new MockMultipartFile("upload", f.getName(), "multipart/form-data",fi1);
    MockMultipartFile secmp = new MockMultipartFile("upload", "response.pdf","application/pdf",fi2); 
    MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    mockMvc.perform(MockMvcRequestBuilders.fileUpload("/response")                
            .file(fstmp)
            .file(secmp))               
            .andExpect(status().isOk());
}
@Test
public void test1() throws Exception {
    MockMultipartFile firstFile = new MockMultipartFile("pdf", "response.pdf", "multipart/form-data", "data".getBytes());
    Path path = Paths.get(env.getProperty("upload.dir.location"));
    MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    mockMvc.perform(MockMvcRequestBuilders.fileUpload("/response", path)
                    .file(firstFile)
                    .param("some-random", "4"))
                .andExpect(status().isOk());
}
}

仍然在说,Java.lang.AsserTionError:状态预期:< 200>但是:< 400>对于两个测试用例。

使用junit,您可以在运行该方法后验证文件存在。

@Test
    public void fileUpload_Success() {
        String fullPath = "C:\test\myFile.txt";
        //Your call here to upload the file.
        org.w3c.dom.Document myFile = buildTestFile();
        ExportFileToDisk exportComponent = new ExportFileToDisk();
        exportComponent.exportXMLFile(myFile, fullPath);
        File f = new File(fullPath);
        boolean fileExists = (f.exists() && !f.isDirectory());
        assertTrue(fileExists);
    }

最新更新