0
我想测试从文件读取和写入文件功能。我的问题是这些功能没有任何参数。直到现在,我只用文件作为参数测试了这种功能。我已经通过其他questins看,发现这些:How to unit test a method that reads a given file,How to test write to file in Java?但他们并没有真正帮助我。我想OT试验的代码是:测试写入文件并从不带参数的文件读取
public void loadData()
{
try(BufferedReader br=new BufferedReader(new FileReader(super.fileName))){
String line;
while((line=br.readLine())!=null){
String[] atributes=line.split(";");
if(atributes.length!=4)
throw new Exception("Linia nu este valida!");
Student t=new Student(atributes[0],atributes[1],atributes[2],atributes[3]);
super.save(t);
}
Thread.sleep(5000);
} catch (Exception e) {
e.printStackTrace();
}
}
public synchronized void writeToFile() {
try (BufferedWriter br = new BufferedWriter(new FileWriter(super.fileName))){
super.entities.forEach(x -> {
try {
br.write(x.studentFileLine());
} catch (IOException e) {
e.printStackTrace();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
任何人都可以给我一个如何测试这个没有文件参数提示?
您提到的帖子解释了一个重要的观点:让您的代码可测试。无法设置文件参数进行测试不会使代码可测试。如果你想保持代码不可测试,你可能会得到一种依靠不良实践的方式。 – davidxxx
如何分配'super.fileName'? – slim
顺便说一句,“属性”中有一个双“t”。我只是指出这一点,因为它在这个来源中经常重复。 – slim