如何模拟IQueryable< T> [英] How do I mock IQueryable<T>

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

问题描述

我正在创建一个公开IQueryable的存储库.在我的单元测试中最好的模拟方法是什么?

I am creating a repository that exposes IQueryable. What is the best way to mock this out for my unit testing?

由于我将RhinoMocks用于其余的模拟对象,因此我尝试执行以下操作:

Since I am using RhinoMocks for the rest of my mock objects, I tried to do the following:

IQueryable<MyObject> QueryObject = 
    MockRepository.GenerateStub<IQueryable<MyObject>>();

虽然这不起作用,所以我尝试这样做:

This doesn't work though so I tried doing this:

IQueryable<MyObject> QueryObject = 
    (new List<MyObject> { new MyObject() }).AsQueryable();

是否有更好的方法可以做到这一点,或者是否有任何其他模拟框架内置了对IQueryable的支持?

Is there a better way to do this, or have any other mocking frameworks built support for IQueryable in?

我的存储库界面如下:

public interface IRepository<T> where T : TableServiceEntity
{
    IQueryable<T> Table { get; }
    void Attach(T existingItem);
    void Delete(T itemToDelete);
    void Insert(T newItem);
    T Load(string partitionKey, string rowKey);
    IEnumerable<T> Load(string partitionKey);
    IEnumerable<T> Query(IQueryable<T> query);
    IEnumerable<T> Last(int count);
    T Last();
    void Update(T item);
}

这是我要测试的方法:

public Post LoadPost(int year, int month, int day, string slug)
{
    var query = from p in _blogRepository.Table
                where 
                    p.PartitionKey == Key.Partition(year, month, day) 
                    && p.Slug == slug
                select p;

    var posts = _blogRepository.Query(query.Take(1));

    return posts.First();
}

这是我现在要进行的测试,它将测试LoadPost.

Then here is the test as I have it right now that will test LoadPost.

[Fact]
public void LoadWillRetrieveByPartitionKeyAndRowKeyWhenUsingUriFormat()
{
    Repository
        .Stub(x => x.Query(Arg<IQueryable<Post>>.Is.Anything))
        .Return(new List<Post> {_post});

    var result = Service.LoadPost(
                            _post.Year(),
                            _post.Month(), 
                            _post.Day(), 
                            _post.Slug);

    Assert.NotNull(result);
}

该代码来自我的 AzureBlog 项目.

推荐答案

我通常会完全按照您最终在测试中所做的来做.在编写测试时,我假设.Net库类可以正常工作,并且不包含错误,因此可以在测试中使用它们.当我需要测试列表,集合,可查询的字典等时,我只需创建真实的东西并填充测试数据即可.它使测试的可读性和编写速度更快,并且老实说,这种风险不存在.

I usually do exactly what you ended up doing in your test. When writing my tests I assume that the .Net library classes work correctly and don't contain bugs, so I can use them in the tests. When I need a test list, collection, queryable, dictionary, etc. I just create the real thing and populate with test data. It makes the tests much more readable and quicker to write, and to be honest the risk is non-existent.

这篇关于如何模拟IQueryable&lt; T&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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