如何对读取给定文件的方法进行单元测试 [英] How to unit test a method that reads a given file
问题描述
我知道这有点天真。如何在不给物理文件作为输入的情况下对这段代码进行单元测试。
我是模拟和单元测试的新手。所以我不确定。请帮忙。
I know this is a bit naive. How to unit test this piece of code without giving physical file as input. I am new to mockito and unit testing. So I am not sure. Please help.
public static String fileToString(File file) throws IOException
{
BufferedReader br = new BufferedReader(new FileReader(file));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append("\n");
line = br.readLine();
}
return sb.toString();
} finally {
br.close();
}
}
推荐答案
你应该重构你的方法。如您所知,将文件作为输入的方法不容易测试。此外,它似乎是静态的,这无助于可测试性。如果您将方法重写为:
You should probably refactor your method. As you realized, a method taking a file as input isn't easily testable. Also, it seems to be static, which doesn't help testability. If you rewrite your method as :
public String fileToString(BufferedReader input) throws IOException
测试会容易得多。您将业务逻辑从读取文件的技术性中分离出来。据我了解,您的业务逻辑是读取流并确保行结尾为unix样式。
it will be much easier to test. You separate your business logic form the technicalities of reading a file. As I understand it, your business logic is reading a stream and ensuring the line endings are unix style.
如果这样做,您的方法将是可测试的。您还可以使它更通用:它现在可以从文件,URL或任何类型的流中读取。更好的代码,更容易测试......
If you do that, your method will be testable. You also make it more generic : it can now read from a file, from a URL, or from any kind of stream. Better code, easier to test ...
这篇关于如何对读取给定文件的方法进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!