我编写了一个Course类,它具有从文本和二进制文件读取的构造函数,并具有向文本和二进制文件写入的方法。我如何编写一个单元测试来测试这个类?
见下面代码:
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;
}
}
当您测试构造函数时,通常只需要以下内容:
- 确保创建的对象包含您期望的值(即您传入的值,或者对它们进行某些计算后产生的数据) 加载到对象中的数据与文件(或另一个InputStream,如果您不想在测试中使用实际文件)中的数据匹配
- 为无效输入抛出异常
除此之外,构造函数没有什么可做的。对于您的第一个构造函数,它只是赋值(不做任何磁盘I/O),我不倾向于测试这些构造函数,因为您真正要验证的是Java中的=
操作符是否有效,我们知道它确实有效。
因此,我只会为第二个构造函数编写涵盖上述情况的测试。
幸运的是,您实际上没有需要文件-因此您可以将PrintWriter
写入StringWriter
, DataInputStream
封装ByteArrayInputStream
等,并在内存中测试所有内容。
另一种选择是在您的测试项目中使用期望输出的资源-总是将写入内存,但然后检查对那些"黄金"文件的期望,您可能应该使用Class.getResource
而不是FileInputStream
加载这些文件(以避免任何文件系统依赖)。