2014-11-25 67 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從應用程序的其餘部分抽象出來。

它後來切換到內存數據庫中進行'實時'測試。

相關問題