0

我目前正在对一个大学注册系统进行单元测试,而当我要测试的方法包含一个将与大学联系并担任调解员的调解员时,它总是会出错。有没有关于如何测试这种方法的想法?

方法是:

public void SelectCourse(List<Course> courses)
    {
        if (this.IsFullTime)
        {
            while (_CurrentCourses.Count < LEAST_NUM_OF_COURSES_FULLTIME)
            {
                Random rand = new Random();
                byte[] b = new byte[1];
                rand.NextBytes(b);
                int i = rand.Next(courses.Count);
                Course c = courses.ToArray()[i];
                ((University)mediator).RegisterStudentForCourse(this, c);
            }
        }
        else
        {
            while (_CurrentCourses.Count < LEAST_NUM_OF_COURSES_PARTTIME)
            {
                Random rand = new Random();
                byte[] b = new byte[1];
                rand.NextBytes(b);
                int i = rand.Next(courses.Count);
                Course c = courses.ToArray()[i];

                // I always //has unit test error with this line!!:
                ((University)mediator).RegisterStudentForCourse(this, c);
            }
        }
        System.Console.WriteLine("Student: "
                                 + this.Name 
                                 + ", with student number: (" 
                                 + this.StudentNumber 
                                 +  ") registered.");
    }
4

1 回答 1

0

正如评论中所建议的,我会在测试中模拟一个大学对象并将其注入到包含这些函数的类中。请记住:您正在尝试测试代码单元......而不是集成测试期间的整个功能链。

另外..我会重构这个..我知道这不是你所要求的..但是它可以使测试更容易并且错误发现不那么混乱:

public ClassThatHousesTheseFunctions(IUniversity university) {
    this._university = university;
}

public void SelectCourse(List<Course> courses) {
    if (this.IsFullTime) {
        performCourseSelection(courses, LEAST_NUM_OF_COURSES_FULLTIME);
    }
    else {
        performCourseSelection(courses, LEAST_NUM_OF_COURSES_PARTTIME);
    }       
}

private void performCourseSelection(IList<Course> courses, int leastNumberOfCourses) {
    Random rand = new Random();

    while (courses.Count < leastNumberOfCourses) {
        int i = rand.Next(courses.Count);
        Course c = courses.ToArray()[i];
        _university.RegisterStudentForCourse(this, c);
    }

    System.Console.WriteLine("Student: " + this.Name + ", with student number: (" + this.StudentNumber + ") registered.");
}
于 2012-09-28T04:12:52.063 回答