存储库模式和来自内存的单元测试 [英] Repository Pattern and unit testing from memory

查看:84
本文介绍了存储库模式和来自内存的单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了一些存储库模式的实现,非常简单直观,在Stackoverflow中链接了其他答案

http://www.codeproject.com/Tips/309753/Repository-Pattern-with-Entity-Framework-4-1-and-C http://www.remondo.net/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)
    }
    

测试时,我希望提供内存上下文。在生产环境中,我将提供一个真实的数据库上下文。

推荐答案

我建议使用MoqRhinoMocks这样的模仿库。可以找到使用Moq的很好的教程here

在您决定使用哪一个之前,以下内容可能会有所帮助:

其他信息:单元测试框架对比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
.....

这篇关于存储库模式和来自内存的单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆