有几个带有单元测试的类。在每个类中,测试应该使用从文件中读取的方法
public static String readFromFile(String fileName){
String result = null;
ClassLoader classLoader = MessageKafkaHandlerTest.class.getClassLoader();
File file = new File(classLoader.getResource(fileName).getFile());
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line = null;
StringBuilder stringBuilder = new StringBuilder();
String ls = System.getProperty("line.separator");
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append(ls);
}
result = stringBuilder.toString();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
在哪里以及如何正确地取出这种方法?解决此类问题的正确方法是什么?
提前致谢。
TestFileUtils您可以在包含您的测试的包中创建一个新的类型类。如果测试位于不同的包中,则选择最顶层的父级。上述代码的一个提示:
不要忽视
IOException。从您将堆栈跟踪输出到控制台这一事实来看,您的测试不会变红,希望有人能用眼睛注意到这一点是不值得的。最好按原样扔掉原件IOException,即 让测试下降。另一种选择是直接catch使用以下方法进行测试fail():