gpt4 book ai didi

c# - 在实体中模拟 ICollection 属性

转载 作者:行者123 更新时间:2023-12-03 20:29:21 27 4
gpt4 key购买 nike

我正在对我的实体执行一些单元测试,我在模拟属性时遇到了一些心理障碍。采取以下实体:

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 个 Bob 分配给该老师。我是这样设置的:

[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的方法|不是虚拟的,因此不能被模拟。我如何模拟此特定功能?

任何帮助总是感激!

最佳答案

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

teacher.Students = Enumerable.Repeat(new Student { Name = "Bob" }, 10)
.ToList();

关于c# - 在实体中模拟 ICollection 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14216027/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com