简体   繁体   中英

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);
    }
}

The above code in which IDepartmentService is of Lazy type and while passing it to constructor it is giving error. As Lazy class type object accessed through ".Value" and in MOQ use ".Object"

Thanks in advance for the help! .

You do not need to mock Lazy object, instead, you mock the object Lazy returns and then create Lazy manually like this:

new Lazy<IDepartmentService>(() => departmentService.Object)

So you get:

private readonly Mock<IDepartmentService> departmentService; 
...
this.student = new Student(new Lazy<IDepartmentService>(() => departmentService.Object), studentRepository.Object, studentService.Object);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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