我是初學者,並且保持在手中。 我需要測試這種方法 - 寫入/讀取/從文件。你能得到建議嗎?我能做得更好,只使用junit測試還是更好的EasyMock?你可以建議做什麼?如何使用EasyMock對文件進行測試寫入/讀取
public class AbsFigure {
public void write(String fileName, List<FigureGeneral> figuresList) {
try {
PrintWriter out = new PrintWriter(
new File(fileName).getAbsoluteFile());
try {
for (int i = 0; i < figuresList.size(); i++) {
out.println(figuresList.get(i).toString());
}
} finally {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
System.out.println("Cannot write to file!");
}
}
// read from file
private ArrayList<FigureGeneral> figureReader(String fileName) {
String line = null;
ArrayList<FigureGeneral> myListFigure = new ArrayList<FigureGeneral>();
try {
File myFile = new File(fileName);
FileReader fileReader = new FileReader(myFile);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while ((line = bufferedReader.readLine()) != null) {
myListFigure.add(fromStringToFigureGeneral(line));
}
System.out.println(myListFigure);
bufferedReader.close();
} catch (FileNotFoundException e) {
System.out.println("File which You loking for not found!");
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (IOException e) {
System.out.println("Wrong input!");
}
return myListFigure;
}
// change from String to FigureGeneral(Triangle or Rectangle)
private FigureGeneral fromStringToFigureGeneral(String line) {
String[] arrayLines = line.split(" ");
FigureGeneral figures = null;
if (arrayLines[0].equals("triangle")) {
figures = new Triangle(Double.parseDouble(arrayLines[1]),
Double.parseDouble(arrayLines[2]), "triangle");
} else {
figures = new Rectangle(Double.parseDouble(arrayLines[1]),
Double.parseDouble(arrayLines[2]), "rectangle");
}
return figures;
}
public void launch(AbsFigure absFigure) {
List<FigureGeneral> figuresList = absFigure.generateRandomFigures(5);
AreaCompare areaCompare = new AreaCompare();
Collections.sort(figuresList, areaCompare);
absFigure.write("test.txt", figuresList);
figureReader("test.txt");
}
public static void main(String[] args) {
AbsFigure absFigure = new AbsFigure();
absFigure.launch(absFigure);
}
}
我寫了更多的代碼,並且可以更好地減少情況。我希望你可以推薦如何測試這個(也許你可以展示兩種變體)。
而是嘲諷的類,它是遠遠易於使用的臨時文件。 –
我會讓'figureReader'返回一個'List',我會一直打印出這個異常,除非你添加,而不是放棄信息。 ;)我會將任何附加信息寫入'System.err',因爲你是默認情況下寫入Exceptions的地方。 –