我看到了一些存储库模式的实现,非常简单直观,在Stackoverflow中链接了其他答案
www.codeproject/Tips/309753/Repository-Pattern-with-Entity-Framework-4-1-and-C www.remondo/repository-pattern-example-csharp/
public interface IRepository<T> { void Insert(T entity); void Delete(T entity); IQueryable<T> SearchFor(Expression<Func<T, bool>> predicate); IQueryable<T> GetAll(); T GetById(int id); } public class Repository<T> : IRepository<T> where T : class, IEntity { protected Table<T> DataTable; public Repository(DataContext dataContext) { DataTable = dataContext.GetTable<T>(); } ...如何在进行单元测试时将其设置为在内存中工作?有没有办法从内存中的任何东西构建DataContext或Linq表?我的想法是创建一个集合(列表、词典...)并在单元测试时将其存根。
谢谢!
编辑: 我需要这样的东西:
- 我有一本课本
- 我有一个类库
在Library构造函数中,我初始化存储库:
var bookRepository = new Repository<Book>(dataContext)
和Library方法使用存储库,如下所示
public Book GetByID(int bookID) { return bookRepository.GetByID(bookID) }
测试时,我希望提供内存上下文。在生产环境中,我将提供一个真实的数据库上下文。
推荐答案我建议使用Moq或RhinoMocks这样的模仿库。可以找到使用Moq的很好的教程here。
在您决定使用哪一个之前,以下内容可能会有所帮助:
graemef/blog/2011/02/10/A-quick-comparison-of-some-.NET-mocking-frameworks/
jimmykeen/articles/09-jul-2012/mocking-frameworks-comparison-part-1-introduction
其他信息:单元测试框架对比here。
更新跟随OP的请求
创建内存数据库
var bookInMemoryDatabase = new List<Book> { new Book() {Id = 1, Name = "Book1"}, new Book() {Id = 2, Name = "Book2"}, new Book() {Id = 3, Name = "Book3"} };模拟存储库(我在下面的示例中使用了Moq)
var repository = new Mock<IRepository<Book>>();设置存储库
// When I call GetById method defined in my IRepository contract, the moq will try to find // matching element in my memory database and return it. repository.Setup(x => x.GetById(It.IsAny<int>())) .Returns((int i) => bookInMemoryDatabase.Single(bo => bo.Id == i));通过在构造函数参数中传递模拟对象来创建库对象
var library = new Library(repository.Object);最后几个测试:
// First scenario look up for some book that really exists var bookThatExists = library.GetByID(3); Assert.IsNotNull(bookThatExists); Assert.AreEqual(bookThatExists.Id, 3); Assert.AreEqual(bookThatExists.Name, "Book3"); // Second scenario look for some book that does not exist //(I don't have any book in my memory database with Id = 5 Assert.That(() => library.GetByID(5), Throws.Exception .TypeOf<InvalidOperationException>()); // Add more test case depending on your business context .....更多推荐
存储库模式和来自内存的单元测试
发布评论