使用c#包含中介的单元测试方法

时间:2012-09-28 03:05:30

标签: c# visual-studio-2010 unit-testing mediator

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

方法是:

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.");
    }

1 个答案:

答案 0 :(得分:0)

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

另外..我会重构这个..我知道这不是你要求的......但是它可以使测试更容易,并且发现bug更少杂乱:

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.");
}