Mocking DbContext.Set<T>()?

你说的曾经没有我的故事 提交于 2019-12-18 20:06:38

问题


We're using EF Code first, and have a data context for our sales database. Additionally, we have a class that sits on top of our data context and does some basic CRUD operations.

For example, we have the following function:

public static T Create<T>(int userId, T entity) where T : class, IAllowCreate
{
    if (entity == null)
        throw new ArgumentNullException("entity");

    using (SalesContext dc = new SalesContext())
    {
         dc.Set<T>().Add(entity);
         dc.SaveChanges();

         return entity;
    }
}

I found an example of how to create fake contexts and IDBset properties. I started implementing that, but I ran in to an issue.

We use dc.Set() quite liberally (as seen above) in our code, as we attempt to create generic CRUD methods. Instead of having a ReadCustomer, ReadContact etc, we would just do Read(). However, dc.Set returns a DbSet, not an IDbSet, so I'm not able to mock that.

Has anyone been able to mock or fake DbContext and still use the Set functionality?


回答1:


interface ISalesContext
{
    IDbSet<T> GetIDbSet<T>();
}

class SalesContext : DbContext, ISalesContext
{
    public IDbSet<T> GetIDbSet<T>()
    {
        return Set<T>();
    }
}

I used a different name, but you can use the new operator if you prefer to hide the regular implementation.



来源:https://stackoverflow.com/questions/5007100/mocking-dbcontext-sett

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!