我想使用JUnit测试用例来测试文件上传组件。我可以使用下面的ode从UI中读取上传的文件来获取UploadedFile.i的模拟实现。
public void XXXX(final FileUploadEvent event) {
final String uniqueFolderName = this.getUniqueFolderName();
final org.primefaces.model.UploadedFile uploadedFile = event.getFile();
final UploadedFileWrapper uploadedFileWrapper = new UploadedFileWrapper(uploadedFile,
UploadedFile.Status.FILE_SAVED, uniqueFolderName);
if (!new Boolean(this.multiple)) {
LOGGER.debug("only single upload is allowed", this.getMultiple());
this.clearUploadedFiles();
}
this.uploadedFiles.add(uploadedFileWrapper);
}
你能帮我解决一下如何为这个组件创建模拟实现。
答案 0 :(得分:3)
这就是Mockito所做的:
File file = new File("src/test/TestUploadFile.txt");
InputStream inputStream = new FileInputStream(file);
FileUploadEvent event = Mockito.mock(FileUploadEvent.class);
UploadedFile uploadedFile = Mockito.mock(UploadedFile.class);
Mockito.when(uploadedFile.getFileName()).thenReturn(file.getName());
Mockito.when(uploadedFile.getContentType()).thenReturn("application/octet-stream");
Mockito.when(uploadedFile.getInputstream()).thenReturn(inputStream);
Mockito.when(event.getFile()).thenReturn(uploadedFile);
我拉一个测试文件并创建一个inputStream。然后我模拟FileUploadEvent和UploadedFile并设置我需要的特定属性,您可能需要模拟更多属性。
答案 1 :(得分:1)
Did you try..
// Creating a Mock for UploadedFile
UploadedFile mockFileUploadedFile = EasyMock.createMock(UploadedFile.class);
// Injecting the Mock to FileUploadEvent
FileUploadEvent fileUploadEvent = new instance...
fileUploadEvent.setFileUploadedFile(mockFileUploadedFile)