如何从模拟路径加载模拟文件 [英] How to load a mock file from mock path

查看:108
本文介绍了如何从模拟路径加载模拟文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个函数的单元测试,该函数试图从磁盘中获取文件并将其流式传输:

I am trying to write unit test for a function which trys to get a file from disk and streaming it:

public InputStream downloadFile(String folderName, String fileName) throws FileNotFoundException {
    File name = Paths.get("/tmp/portal", folderName, fileName).toFile();

    return new FileInputStream(name);
  }

我的尝试代码

 @InjectMock MyService myService;
   
    @TempDir
        Path mockDirectory;
     @Test
        void downloadFile() throws IOException {
     Path mockFile = mockDirectory.resolve("testFile");
            Files.createFile(mockFile);
     String folderName= mockFile.subpath(5, 6).toString();
     String filename= mockFile.getFileName().toString();
        InputStream inputStreamResult = myService.downloadFile(folderName, filename);
    }

错误是

文件:testFile不存在

File: testFile dont exsits

推荐答案

您收到错误testFile dont exsits,因为在downloadFile方法中有一个硬编码的路径"/tmp/portal".

You receive an error testFile dont exsits, because there is a hard-coded path "/tmp/portal" in downloadFile method.

下面是对文件下载进行单元测试的示例:

Below is an example of unit-testing that file is downloaded:

interface Service {
    Cipher getDecryptCipher();
}

class FileDownloader {

    private final Service service;

    public FileDownloader(Service service) {
        this.service = service;
    }

    public InputStream downloadFile(String folderName, String fileName) throws FileNotFoundException {
        File file = Paths.get(folderName, fileName).toFile();
        return new CipherInputStream(new FileInputStream(file), service.getDecryptCipher());
    }
}

@ExtendWith(MockitoExtension.class)
class FileDownloaderTest {

    @TempDir
    Path directory;
    @Mock
    Service service;
    @Mock
    Cipher cipher;
    @InjectMocks
    FileDownloader fileDownloader;

    @Test
    void fileContentIsDownloaded() throws IOException {

        String testFileName = "testFile";
        String testFileContent = "test text";

        Path testFile = directory.resolve(testFileName);
        Files.createFile(testFile);
        Files.write(testFile, testFileContent.getBytes());
        when(service.getDecryptCipher()).thenReturn(cipher);

        InputStream actualInputStream = fileDownloader.downloadFile(directory.toString(), testFileName);

        CipherInputStream expectedInputStream = new CipherInputStream(new ByteArrayInputStream(testFileContent.getBytes()), cipher);
        assertThat(actualInputStream).hasSameContentAs(expectedInputStream);
    }
}

这篇关于如何从模拟路径加载模拟文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆