模拟实体中的ICollection属性

Pau*_*ann 2 c# unit-testing moq mocking

我正在对我的实体进行一些单元测试,并且我有一些精神块嘲弄一个属性.采取以下实体:

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; }
}
Run Code Online (Sandbox Code Playgroud)

我有一个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);
}
Run Code Online (Sandbox Code Playgroud)

我想单元测试这种使用起订量嘲笑-特别是我想嘲弄.Count的方法Teacher.Students,我可以通过它的任何表达式,它会返回一个数字表明,目前有分配给老师10个鲍勃.我这样设置:

[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" });
}
Run Code Online (Sandbox Code Playgroud)

我期待我的自定义异常,但我实际上得到的是System.NotSupportedException推断该.Count方法ICollection不是虚拟的,因此无法模拟.我如何模拟这个特定的功能?

任何帮助总是赞赏!

Dan*_*rth 6

您无法模拟Count正在使用的方法,因为它是一种扩展方法.它不是定义的方法ICollection<T>.
最简单的解决方案是简单地为Students属性分配一个包含10个bobs的列表:

teacher.Students = Enumerable.Repeat(new Student { Name = "Bob" }, 10)
                             .ToList();
Run Code Online (Sandbox Code Playgroud)