NHibernate测试,模拟ISession [英] NHibernate testing, mocking ISession

查看:83
本文介绍了NHibernate测试,模拟ISession的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用NHibernate和Rhinomocks,无法测试我想要的东西.我想在不访问数据库的情况下测试以下存储库方法(其中_session作为ISession注入到存储库中):

I am using NHibernate and Rhinomocks and having trouble testing what I want. I would like to test the following repository method without hitting the database (where _session is injected into the repository as ISession):

public class Repository : IRepository
{
    (... code snipped for brevity ...)

    public T FindBy<T>(Expression<Func<T, bool>> where)
    {  
        return _session.Linq<T>().Where(where).FirstOrDefault();
    }
}

我的初始方法是模拟ISession,并在调用Linq时返回一个IQueryable存根(手工编码).我有一个想在内存中查询的Customer对象的IList,以测试我的Linq查询代码,而无需点击数据库.而且我不确定这会是什么样子.我是否编写自己的IQueryable实现?如果是这样,有人为此方法做过吗?还是我需要看看其他途径?

My initial approach is to mock ISession, and return an IQueryable stub (hand coded) when Linq is called. I have a IList of Customer objects I would like to query in memeory to test my Linq query code without hitting the db. And I'm not sure what this would look like. Do I write my own implementation of IQueryable? If so, has someone done this for this approach? Or do I need to look at other avenues?

谢谢!

推荐答案

我完成此测试的方法是不将表达式传递给存储库,而是公开IQueryable,为存储库提供接口,例如:

How I've done this test is to not pass the expression to the repository, instead expose IQueryable giving the repository an interface such as:

public interface IRepository<T>
{
    IQueryable<T> All();
    // whatever else you want
}

易于实现,例如:

public IQueryable<T> All()
{
    return session.Linq<T>();
}

这意味着您不必像在存储库上那样调用您的方法:

This means that instead of calling your method on the repository like:

var result = repository.FindBy(x => x.Id == 1);

您可以这样做:

var result = repository.All().Where(x => x.Id == 1);

或LINQ语法:

var result = from instance in repository.All()
             where instance.Id == 1
             select instance;

然后,这意味着您可以通过直接模拟存储库来获得相同的测试,这应该更容易.您只需获得模拟即可返回已创建并在其上调用AsQueryable()的列表.

This then means you can get the same test by mocking the repository out directly which should be easier. You just get the mock to return a list you have created and called AsQueryable() on.

正如您所指出的那样,这样做的目的是让您测试查询的逻辑而无需涉及数据库,这会大大降低查询的速度.

As you have pointed out, the point of this is to let you test the logic of your queries without involving the database which would slow them down dramatically.

这篇关于NHibernate测试,模拟ISession的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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