gpt4 book ai didi

java - 如何编写mockito测试用例来上传文件,如下面给定的 Controller 所示?

转载 作者:太空宇宙 更新时间:2023-11-04 11:10:25 27 4
gpt4 key购买 nike

@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(最好)测试用例来测试此代码。我尝试了几种格式,但到目前为止还没有找到完美的一种。有人可以建议我编写用于上传文件的单元测试用例吗?提前致谢!

编辑-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);
}

关于java - 如何编写mockito测试用例来上传文件,如下面给定的 Controller 所示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46076929/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com