我正在尝试为一个简单的方法编写 Junit,该方法将文件名作为输入并返回字节数组作为输出。我面临的困难是运行 Junit 时该文件将不可用。那么,我该如何测试这个方法呢? 我看到两个选项:
- 以某种方式使该文件可用于 Junit(我不确定这是否可行)。
- 模拟/ stub 行为。
我粘贴以下方法的代码:
public byte[] readFileAndReturnBytes(String filePath) throws IOException {
InputStream is = null;
File file = null;
byte[] fileBytes = null;
try
{
file = new File(filePath);
is = new FileInputStream(file);
fileBytes = IOUtils.toByteArray(is);
}
catch(IOException e){
throw e;
}
finally{
if(is != null)
{
is.close();
file = null;
}
}
return fileBytes;
}
我正在使用 Mockito 进行模拟。有人有什么想法吗?
最佳答案
对我来说,最好的选择是重构您的方法,以便它接收 File
而不是 String filePath
。在这种情况下,您可以模拟您的文件并调用方法readFileAndReturnBytes(mockedFile)
。
File mockedFile = mock(File.class);
testClass.readFileAndReturnBytes(mockedFile);
如果你不想重构你的代码,我建议你检查JUnit TempopratyFolder .
关于java - 如何为读取文件并给出字节内容的方法编写 Junit 测试用例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36769106/