简体   繁体   中英

How I can unit-test my entity context

I am working on entity framework and want to unit-test my application. The problem is EntityContext. I am using Moq library. Moq can be used on interfaces and abstract classes. But the problem here is EntityContext is derived from DbContext which is neither abstract class nor interface. How I can provide a moq object for the context. I tried to find the best practice but most of the posts were quite old (2, 3 years old). I am using EF 5.0, I am supposing that Microsoft or others should have done something to test EntityContext.

public class Repository
{
private EntityContext _context;
public EntityContext Context;

    public Repository()
    {
        _context = new EntityContext();
    }

    internal Repository(MockContext mockContext)  // Mock Context. Is it possible?
    {
        _context = mockContext;
    }
}

Note: Sorry for repeat question, but I was not able to find recent questions on this topic.

What I would do is make EntityContext implement an interface. Lets say that the EntityContext exposes a list of Employees and a list of Departments. You would do something like:

public interface IEntityContext
{
    IQueryable Departments { get; set;}
    IQueryable Employees { get; set;}
}

In your repository expect an IEntityContext implementation. In production code send the real implementation, EntityContext. In unit tests send Mock<IEntityContext>().Object after specifying you expectations. Another option is to implement a FakeEntityContext that implements IEntityContext and serves as an in memory DB in your unit tests.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM