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查詢?
對於單元測試,我使用https://effort.codeplex.com/ – Marthijn 2014-11-25 08:35:13