如何在JUnit中模拟Files.copy方法

问题描述 投票:0回答:1

我正在使用Files类的某些方法(例如删除,复制方法)来执行文件的上传和删除操作。下面是执行这些操作的代码。

public String uploadFile(MultipartFile file) {
    try {
    String fileName = file.getOriginalFilename()
        // Copy file to the target location (Replacing existing file with the same name)
        Path targetLocation = Paths.get("uploadPath" + File.separator + StringUtils.cleanPath(fileName));
        Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);

        return fileName;
    } catch (IOException ex) {
        throw new FileStorageException("Not able to upload", ex);
    }
}

但是对于此源代码,我无法编写JUnit测试,因为无法模拟Files类。对于模拟最终类,我们可以使用PowerMock支持模拟静态和最终方法。但是在这里,如果我确实使用PowerMock,它仍然不是在模拟。我正在使用Spring Framework 5.2.1.RELEASE,此版本的JUnit中是否有任何更改可以模拟最终的类或方法?或者有人可以帮助我编写此代码的单元测试(我使用的是Spring Framework 5.2.1和JUnit4.12版本)。

spring junit4
1个回答
0
投票

仅使用PowerMock或PowerMockito之类的工具确实可以模拟静态和最终类,并且与JUnit或Spring框架无关。

我认为您不应该模拟Files.copy操作。而是考虑以下策略:

定义用于处理文件的接口,一种DAO,但用于文件系统:

public interface FileSystemDAO {
   void copy(InputStream is, Path target, StandardCopyOption ... options);
}

public class FileSystemDAOImpl implements FileSystemDAO {
    void copy(InputStream is, Path target, StandatadCopyOption ... options) {
      Files.copy(...)
    }
}

现在在所有处理文件的地方使用依赖项注入(如果您已经说过,请使用spring-将FileSystemDAOImpl定义为bean)。

class MySampleUploadService {

 private final FileSystemDAO fileSystemDao;

 public MySampleUploadService(FileSystemDAO dao) {
      this.fileSystemDao = dao;
 }
 public String uploadFile(MultipartFile file) {
     try {
     String fileName = file.getOriginalFilename()
         // Copy file to the target location (Replacing existing file with the same name)
         Path targetLocation = Paths.get("uploadPath" + File.separator + 
 StringUtils.cleanPath(fileName));
         fileSystemDao.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);

        return fileName;
    } catch (IOException ex) {
        throw new FileStorageException("Not able to upload", ex);
    }
 }

}

现在,通过这种方法,您可以通过模拟FileSystemDao界面轻松测试上传服务。

© www.soinside.com 2019 - 2024. All rights reserved.