使用MOQ进行模拟时如何将Lazy的类对象类型传递给构造函数

时间:2018-10-24 11:36:26

标签: c# unit-testing dependency-injection moq

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”

预先感谢您的帮助!

1 个答案:

答案 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);