0

我编写了一个 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;
}

}

4

2 回答 2

1

当您测试构造函数时,您通常只需要以下内容:

  • 确保创建的对象包含您期望的值(即您传入的值,或对它们进行的某些计算产生的数据)
  • 加载到对象中的数据与文件中的数据匹配(或另一个 InputStream,如果您不想在测试中使用实际文件)
  • 无效输入引发异常

除此之外,构造函数没有什么可做的。对于您的第一个构造函数,它只是分配值(不进行任何磁盘 I/O),我不倾向于测试这些构造函数,因为您真正要验证的是=Java 中的运算符是否有效,我们知道这是做。

因此,我只会为您的第二个构造函数编写涵盖上述情况的测试。

于 2011-09-19T15:02:36.610 回答
1

幸运的是,您实际上并不需要文件 - 因此您可以将PrintWriter写入传递给 a StringWriter,并DataInputStream包装 aByteArrayInputStream等,并测试内存中的所有内容。

另一种选择是在您的测试项目中拥有具有预期输出的资源 - 始终写入内存,然后检查那些“黄金”文件的预期,您可能应该使用Class.getResource而不是 a加载FileInputStream这些文件(以避免具有任何文件系统依赖性)。

于 2011-09-19T15:00:55.073 回答