I am doing a simple unit test where, when creating a Course, the Title field cannot be empty. I have to test it with a service class that has dependency injection with UnitOfWork. When I debug my test, I get an exception error from Can not instantiate proxy of class: ContosoUniversity.Models.CourseRepository . I was looking for an error but cannot figure out how to fix the problem and Assert statement?
Error message 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);
Afton source share