簡體   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