2014-11-25 34 views
3

有人说我们不应该使用存储库和工作单元模式,因为存储库& UnitOfWork只是复制了实体框架(EF)DbContext给你的东西。 但是,如果使用存储库,我可以写服务容易单元测试,因为我可以模拟从库法(其中使用LINQ查询从数据库返回的数据),例如:你是否在Entity Framework中使用存储库模式?

库:

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(); 
    } 
} 

服务:

[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); 
    } 
} 

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; 
    } 
} 

服务单元测试

现在,当我消除库我必须写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查询?

+0

对于单元测试,我使用https://effort.codeplex.com/ – Marthijn 2014-11-25 08:35:13

回答

4

与所有模式一样,如果它适合您的目的,那么您应该使用它。

我写了一个包装实体框架的工作单元和存储库模式实现。不仅如此,我可以进行测试,而是将EF从应用程序的其余部分抽象出来。

它后来切换到内存数据库中进行'实时'测试。

相关问题