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

Spring 如何在JUnit中模拟Files.copy方法,spring,junit4,Spring,Junit4,我正在使用文件类的一些方法(删除、复制方法)来上传和删除文件。下面是执行这些操作的代码 public String uploadFile(MultipartFile file) { try { String fileName = file.getOriginalFilename() // Copy file to the target location (Replacing existing file with the same name) Pat

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

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测试,因为我不能模拟
文件
类。对于模拟最终类,我们可以使用PowerMock,它支持模拟静态和最终方法。但在这里,如果我使用PowerMock,它仍然不是mock。我使用的是SpringFramework5.2.1.RELEASE,这个版本的JUnit中是否有任何更改来模拟最终的类或方法?或者有谁能帮我编写这段代码的单元测试(我使用的是Spring Framework 5.2.1和JUnit4.12版本)。

模拟静态类和最终类确实只可能使用PowerMock或PowerMockito之类的工具,而与JUnit或Spring框架无关

我认为你不应该模仿
文件。复制
操作。
取而代之的是考虑以下策略:

定义一个用于处理文件的接口,一种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)

现在使用这种方法,您可以通过模拟
FileSystemDao
接口轻松地测试上传服务

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

}