Unable to generate proxy class error code

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); //var error = _modelState["Title"].Errors[0]; //Assert.AreEqual("The Title field is required.", error.ErrorMessage); //mockRepo.Setup(x => x.Insert(course)); } 
+5
source share
1 answer

The error indicates that the CourseRepository cannot be initialized because it does not have a constructor with a lower value. The Mocking framework is looking for a constructor with a smaller design to create a mock object.

If your class does not have a constructor without parameters, you need to pass these parameters when creating the Mock. In your case, the mock from CourseRepository will be created as follows.

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

Instead of null, you can also pass the layout of the constructor parameter objects.

+8
source

Source: https://habr.com/ru/post/1264259/


All Articles