2017-02-15 110 views
5

我正在做一個簡單的單元測試,在創建課程時,標題字段不能爲空。我必須使用具有UnitOfWork的依賴注入的服務類進行測試。當我調試我的測試時,我得到一個異常錯誤Can not instantiate proxy of class: ContosoUniversity.Models.CourseRepository我查看了這個錯誤,但是我無法理解如何解決這個問題和Assert語句?無法實例化類錯誤代理

Error Message Display Image

CourseRepository

public class CourseRepository : GenericRepository<Course> 
{ 
    public CourseRepository(SchoolContext context) 
     : base(context) 
    { 
    } 

的UnitOfWork

public class UnitOfWork : IDisposable, IUnitOfWork 
{ 
    private SchoolContext context = new SchoolContext(); 
    private GenericRepository<Department> departmentRepository; 
    private CourseRepository courseRepository; 

    public CourseRepository CourseRepository 
    { 
     get 
     { 
      if (this.courseRepository == null) 
      { 
       this.courseRepository = new CourseRepository(context); 
      } 
      return courseRepository; 
     } 
    } 

    public virtual CourseRepository GetCourseRepository() 
    { 
     if (this.courseRepository == null) 
     { 
      this.courseRepository = new CourseRepository(context); 
     } 
     return courseRepository; 
    } 

CourseService

public class CourseService : ICourseService 
{ 
    private IUnitOfWork unitOfWork; 

    public CourseService (IUnitOfWork unitOfWork) 
    { 
     this.unitOfWork = unitOfWork; 
    } 

    public void Create(Course course) 
    { 
     unitOfWork.GetCourseRepository().Insert(course); 
     unitOfWork.Save(); 
    } 

    public Course GetCourseByID(int id) 
    { 
     return unitOfWork.GetCourseRepository().GetByID(id); 
    } 

TestMethod的

[TestMethod] 
public void TestMethod1() 
{ 
    var course = new Course 
    { 
     CourseID = 2210, 
     Title = string.Empty, 
     Credits = 3, 
     DepartmentID = 1 
    }; 

    Mock<CourseRepository> mockRepo = new Mock<CourseRepository>(); 
    mockRepo.Setup(m => m.GetByID(course.CourseID)).Returns(course); 

    var mockUnit = new Mock<IUnitOfWork>(); 
    mockUnit.Setup(x => x.GetCourseRepository()).Returns(mockRepo.Object); 

    var myService = new CourseService(mockUnit.Object); 
    myService.Create(course); 

    //var error = _modelState["Title"].Errors[0]; 
    //Assert.AreEqual("The Title field is required.", error.ErrorMessage); 

    //mockRepo.Setup(x => x.Insert(course)); 
} 

回答

8

錯誤說,CourseRepository不能初始化,因爲它沒有參數的構造函數。模仿框架首先查找參數較少的構造函數來創建模擬對象。

如果你的類沒有無參數構造函數,那麼當你創建模擬時你需要傳遞這些參數。在你的情況下,模擬CourseRepository將被創建如下。

var repositoryMock = new Mock<CourseRepository>(null); 

而不是null,您還可以傳遞構造函數參數的模擬對象。

+1

這應該被標記爲答案 –

相關問題