public class StudentTests
{
private readonly Mock<IStudentRepository> studentRepository;
private readonly Mock<Lazy<IDepartmentService>> departmentService;
private readonly Mock<IStudentService> studentService;
private readonly Student student;
public StudentTests()
{
this.studentRepository = new Mock<IStudentRepository>();
this.departmentService = new Mock<Lazy<IDepartmentService>>();
this.studentService = new Mock<IStudentService>();
this.student = new Student(departmentService.Object, studentRepository.Object, studentService.Object);
}
}
上面的代码,其中IDepartmentService是Lazy类型,当将其传递给构造函数时,它给出了错误。作为通过“ .Value”访问的惰性类类型对象,在MOQ中使用“ .Object”
预先感谢您的帮助!
答案 0 :(得分:3)
您无需模拟Lazy
对象,而是模拟Lazy
返回的对象,然后手动创建Lazy
,如下所示:
new Lazy<IDepartmentService>(() => departmentService.Object)
所以您得到:
private readonly Mock<IDepartmentService> departmentService;
...
this.student = new Student(new Lazy<IDepartmentService>(() => departmentService.Object), studentRepository.Object, studentService.Object);