我正在进行一个简单的单元测试,在创建课程时,Title字段不能为空。我不得不使用具有UnitOfWork的依赖注入的服务类来测试它。当我调试我的测试时,我收到Can not instantiate proxy of class: ContosoUniversity.Models.CourseRepository
的异常错误我调查了错误,但是我无法理解如何修复问题和Assert语句?
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));
}
答案 0 :(得分:38)
错误表明 find: paths must precede expression: tail
Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec] [path...] [expression]
无法初始化,因为它没有参数较少的构造函数。模拟框架首先查找参数较少的构造函数以创建模拟对象。
如果你的类没有无参数构造函数,那么你需要在创建Mock时传递这些参数。在您的情况下,CourseRepository
的模拟将创建如下。
CourseRepository
您也可以传递构造函数参数的模拟对象,而不是null。
答案 1 :(得分:1)
或者,如果您的类具有内部无参数构造函数,则需要将InternalsVisibleTo
属性添加到程序集。
如果是Moq,请添加以下内容:
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
或者这,如果您需要一个强钥匙
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2,PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")]
答案 2 :(得分:0)
在嘲笑时只需使用接口。
Mock<ICourseRepository> mockRepo = new Mock<ICourseRepository>();
mockRepo.Setup(m => m.GetByID(course.CourseID)).Returns(course);