我编写了一个Course类,它包含从文本和二进制文件中读取的构造函数,并具有写入文本和二进制文件的方法。如何编写junit测试来测试这个类?
请参阅以下代码:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.PrintWriter;
import java.util.Scanner;
public class Course {
//instance variables
private String courseID;
private String courseName;
private int numberOfCredits;
private String departmentID;
public Course(String courseID,String courseName, int numberOfCredits, String departmentID){
//constructor
this.courseID=courseID;
this.courseName=courseName;
this.numberOfCredits=numberOfCredits;
this.departmentID=departmentID;
}
public Course(Scanner inputFile)throws Exception{
//constructor, read data from text file
try{
courseID=inputFile.nextLine();
courseName=inputFile.next();
numberOfCredits=inputFile.nextInt();
departmentID=inputFile.next();
}
catch(Exception e){
throw e;
}
}
public Course (DataInputStream binFile)throws Exception{
//constructor reads from binary file and assign values to variables
try{
courseID=binFile.readUTF();
courseName=binFile.readUTF();
numberOfCredits=binFile.readInt();
departmentID=binFile.readUTF();
}
catch(Exception e){
throw e;
}
}
public void saveToTextFile(PrintWriter file){
//prints to text file
file.printf(" %s %s %d %s ", courseID, courseName, numberOfCredits, departmentID);
}
public void saveToBin(DataOutputStream binFile)throws Exception{
//saves information to binary file
binFile.writeUTF(courseID);
binFile.writeUTF(courseName);
binFile.writeInt(numberOfCredits);
binFile.writeUTF(departmentID);
}
public String toString(){
//setup string for course display
String info=courseID + " " + courseName+ " "+ numberOfCredits+" "+ departmentID;
return info;
}
//getters and setters
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public int getNumberOfCredits() {
return numberOfCredits;
}
public void setNumberOfCredits(int numberOfCredits) {
this.numberOfCredits = numberOfCredits;
}
public String getDepartmentID() {
return departmentID;
}
public void setDepartmentID(String departmentID) {
this.departmentID = departmentID;
}
public String getCourseID() {
return courseID;
}
}
答案 0 :(得分:1)
幸运的是,您实际上并没有必需的文件 - 因此您可以将PrintWriter
写入StringWriter
,并DataInputStream
包裹ByteArrayInputStream
{1}}等,并测试内存中的所有内容。
另一种选择是在测试项目中使用期望的输出 - 始终写到内存中,但是然后检查对那些“黄金”文件的期望应该使用Class.getResource
而不是FileInputStream
加载(以避免任何文件系统依赖)。
答案 1 :(得分:1)
当您测试构造函数时,通常只需要以下内容:
除此之外,构造函数没什么可做的。在你的第一个构造函数的情况下,它只是分配值(没有做任何磁盘I / O)我不倾向于测试那些构造函数,因为所有你真正验证的是Java中的=
运算符的工作原理,我们知道的确如此。
所以,我只会为你的第二个构造函数编写涵盖上述情况的测试。