我正在对我的实体执行一些单元测试,并且我在模拟一个属性时有点精神障碍。采取以下实体:
public class Teacher
{
public int MaxBobs { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
public class Student
{
public string Name { get; set; }
public virtual Teacher Teacher { get; set; }
}
我有一个Teacher
调用方法,AddStudent
它首先检查老师是否分配了太多名为 Bob 的学生。如果是这样,那么我会提出一个自定义异常,说太多鲍勃。该方法如下所示:
public void AddStudent(Student student)
{
if (student.Name.Equals("Bob"))
{
if (this.Students.Count(s => s.Name.Equals("Bob")) >= this.MaxBobs)
{
throw new TooManyBobsException("Too many Bobs!!");
}
}
this.Students.Add(student);
}
我想使用Moq模拟对此进行单元测试——特别是我想模拟我可以将任何表达式传递给它的.Count
方法,Teacher.Students
它会返回一个数字,表明目前有 10 个 Bobs 分配给了那个老师。我是这样设置的:
[TestMethod]
[ExpectedException(typeof(TooManyBobsException))]
public void Can_not_add_too_many_bobs()
{
Mock<ICollection<Student>> students = new Mock<ICollection<Student>>();
students.Setup(s => s.Count(It.IsAny<Func<Student, bool>>()).Returns(10);
Teacher teacher = new Teacher();
teacher.MaxBobs = 1;
// set the collection to the Mock - I think this is where I'm going wrong
teacher.Students = students.Object;
// the next line should raise an exception because there can be only one
// Bob, yet my mocked collection says there are 10
teacher.AddStudent(new Student() { Name = "Bob" });
}
我期待我的自定义异常,但我实际上得到的是System.NotSupportedException
它推断.Count
方法ICollection
不是虚拟的,因此不能被模拟。我如何模拟这个特定的功能?
任何帮助总是很感激!