繁体   English   中英

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

[英]How to pass class object type of Lazy to constructor while mocking using 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”访问的Lazy类类型对象

先谢谢您的帮助!

你不需要模拟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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM