我是初学者,请自己掌握。我需要测试这个方法 - 写入/读取到/从文件。你能得到建议吗?我能做多好,只使用junit测试或更好的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);
}
}
我写了更多的代码,你可以更好地理解情况。我希望您可以推荐如何测试它(也许您可以显示两个变体)。