您如何使用moq模拟将项目添加到存储库或DbContext? [英] How do you mock adding items to a repository or DbContext using moq?

查看:156
本文介绍了您如何使用moq模拟将项目添加到存储库或DbContext?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我所看到的使用moq作为存储库的示例仅显示了如何模拟返回的内容.我有一个奇怪的要求:执行查询时,如果存在条件,则应将某个项目添加到存储库中.我想知道如何在不查询数据库的情况下进行测试.我知道如何模拟现有条件,但是如何设置模拟,以便可以测试是否添加了特定项目?

The examples I've seen for using moq for a repository only show how to mock things being returned. I have a somewhat strange requirement: when a query is executed, if a condition exists, a certain item should be added to the repository. I am wondering how to test this without querying the database. I know how to mock the condition existing, but then how do you setup the mock so that you can test that the certain item is added?

推荐答案

尝试在内存存储库中使用伪造的内容,而不要在最小定额中使用,例如,所有实体的通用通用存储库:

Try to use fake in memory repository instead of moq, for example universal generic repository for all entities:

public interface IInMemoryRepository<T> where T : class
{
    IQueryable<T> GetAll();
    void Create(T item);
    void Update(T item);
    T GetItem(Expression<Func<T, bool>> expression);
    void Delete(T item);
}

public class InMemoryRepository<T> : IInMemoryRepository<T> where T : class
{
    private int _incrementer = 0;
    public Dictionary<int, T> List = new Dictionary<int, T>();

    public IQueryable<T> GetAll()
    {
        return List.Select(x => x.Value).AsQueryable();
    }

    public void Create(T item)
    {
        _incrementer++;
        item.GetType().GetProperties().First(p => p.Name == "Id").SetValue(item, _incrementer, null);
        List.Add(_incrementer, item);
    }

    public void Update(T item)
    {
        var key = (int)item.GetType().GetProperties().First(p => p.Name == "Id").GetValue(item, null);
        List[key] = item;
    }

    public T GetItem(Expression<Func<T, bool>> expression)
    {
        return List.Select(x => x.Value).SingleOrDefault(expression.Compile());
    }

    public void Delete(T item)
    {
        var key = (int)item.GetType().GetProperties().First(p => p.Name == "Id").GetValue(item, null);
        List.Remove(key);
    }
}

这篇关于您如何使用moq模拟将项目添加到存储库或DbContext?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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