0

我想使用 JUnit 测试用例测试文件上传组件。我可以得到 UploadedFile 的模拟实现。我正在使用下面的 ode 从 UI 读取上传的文件。

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

你能帮我如何为这个组件创建模拟实现吗?

4

2 回答 2

4

这是使用 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);

我拉一个测试文件并创建一个输入流。然后我模拟 FileUploadEvent 和 UploadedFile 并设置我需要的特定属性,您可能需要模拟出更多属性。

于 2014-07-25T23:04:50.727 回答
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) 
于 2013-08-06T09:41:41.693 回答