如何测试读取路线和文件并接收日期作为参数的方法:
public String getFileAE(String fecha) {
String fileName = null;
String filePath = null;
File file = null;
try {
logger.info("Leyendo archivo ejecutivos facultados");
fileName = ConstantsFiles.FILE_NAME_AE + fecha + ConstantsFiles.FILE_EXTENSION;
filePath = ConstantsFiles.FILE_PATH_AE + fileName;
logger.info(filePath);
file = new File(filePath);
if (!file.exists()) {
logger.error("Error, el archivo no existe: " + filePath);
return "";
}
return filePath;
} catch (Exception ex) {
logger.error("Error, el archivo no se pudo leer: " + ex.getMessage(), ex);
}
return filePath;
}
你不能模拟
new File(filePath)
,所以你需要将其提取到另一个组件中:
class FileFactoryService {
File newFile(String path) {
return new File(path);
}
}
您在课堂上使用的:
class MyClass {
private final FileFactoryService fileFactoryService;
public MyClass(FileFactoryService fileFactoryService, ...) {
this.fileFactoryService = fileFactoryService;
...
}
public String getFileAE(String fecha) {
...
file = fileFactoryService.newFile(filePath);
...
}
}
然后在你的测试中:
@Test
public void testGetFileAE() {
FileFactoryService fileFactoryService = mock(FileFactoryService.class);
File file = mock(File.class);
when(fileFactoryService.newFile("/the/path/we/expect.ext").thenReturn(file);
when(file.exists()).thenReturn(true);
MyClass myClass = new MyClass(fileFactoryService , ... );
assertEquals("/the/path/we/expect", myClass.getFileAE("expect"));
}