有些人说我们不应该使用存储库和工作单元模式,因为存储库和 UnitOfWork 只是复制 Entity Framework (EF) DbContext 为您提供的内容。 但如果我使用存储库,我可以为服务编写简单的单元测试,因为我可以从存储库模拟方法(使用 linq 查询从数据库返回数据),例如:
存储库:
public class CommentsRepository : ICommentsRepository
{
public CommentsRepository(DatabaseContext context)
: base(context)
{
}
public IEnumerable<Comment> GetComments()
{
return context.Comments.Include(x => x.Note).OrderByDescending(x => x.CreatedDate).ToList();
}
}
服务:
public class CommentsService : ICommentsService
{
private ICommentsRepository _commentsRepository;
public CommentsService(ICommentsRepository commentsRepository)
{
_commentsRepository = commentsRepository;
}
public IEnumerable<Comment> GetComments()
{
List<Comment> comments = _commentsRepository.GetComments().ToList();
comments.ForEach(x => x.Author = "Secret");
return comments;
}
}
服务的单元测试:
[TestClass]
public class CommentsServiceTest
{
[TestMethod]
public void GetCommentsTest()
{
// Arrange
IList<Comment> comments = Builder<Comment>.CreateListOfSize(2)
.Build();
AutoMoqer mocker = new AutoMoqer();
mocker.GetMock<ICommentsRepository>()
.Setup(x => x.GetComments())
.Returns(comments);
// Act
ICommentsService commentsService = mocker.Resolve<CommentsService>();
IList<Comment> result = commentsService.GetComments().ToList();
// Assert
Assert.AreEqual("Secret", result[0].Author);
Assert.AreEqual("Secret", result[1].Author);
}
}
现在,当我删除存储库时,我必须在服务中编写 linq 查询:
public class CommentsService : ICommentsService
{
private DatabaseContext _context;
public CommentsService(DatabaseContext context)
{
_context = context;
}
public IEnumerable<Comment> GetComments()
{
List<Comment> comments = _context.Comments.Include(x => x.Note).OrderByDescending(x => x.CreatedDate).ToList();
comments.ForEach(x => x.Author = "Secret");
return comments;
}
}
为该服务编写单元测试是有问题的,因为我必须模拟:
context.Comments.Include(x => x.Note).OrderByDescending(x => x.CreatedDate)
那你是做什么的?您是否编写存储库类?如果不是,您如何模拟 linq 查询?
最佳答案
与所有模式一样,如果它适合您的目的,那么您应该使用它。
我编写了一个包装 Entity Framework 的工作单元和存储库模式实现。这样我不仅可以进行测试,还可以将 EF 从我的应用程序的其余部分中抽象出来。
这使得后来切换到内存数据库以进行“实时”测试变得轻而易举。
关于c# - 您是否将存储库模式与 Entity Framework 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27121775/