我目前正在對大學註冊系統進行單元測試,而當我要測試的方法包含調解器時,它會始終發生錯誤,該調解器將與作爲調解器的大學聯繫。有沒有關於如何測試這種方法的想法?單元測試方法包含使用c調解器#
的方法是:
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.");
}
隨着[依賴注入](http://en.wikipedia.org/wiki/Dependency_injection),你可以在運行時插入一個模擬'大學'對象進行單元測試。模擬框架的比較在這裏:http://stackoverflow.com/questions/37359/what-c-sharp-mocking-framework-to-use –
@ArunMahapatra依賴注入不是嚴格必須在單元測試中使用模擬對象。 – phoog