简体   繁体   中英

How to mock an interface for entity framework?

I followed the answer here to create a interface for the DbContext in entity framework. The problem is, I have no idea how to use it to unit test. My controller that I am trying to test has two constructors. One has no parameters and sets an IDbContext instance variable to a new DbContext. The other takes an IDbContext and sets the same instance variable. The method I am testing simply does this

return context.EntitySet<question>().ToList();

Below is my failing attempt to use Moq and test the controller. I haven't changed anything in the interface or partial class listed in the answer. Perhaps I need to add something?

            Mock<IDbContext> mockContext = new Mock<IDbContext>();
        question TestQuestion = new question { 
            Id = 1,
            ToAsk = "Did this test work?"
        };
        mockContext.Object.EntitySet<question>().Add(TestQuestion);

        QuestionsController controller = new QuestionsController( mockContext.Object );
        List<DHT.Entity.Models.question> questions = controller.Get();
        Assert.AreEqual(questions.Count, 1);

I am pretty new to .NET and C#, so if I am doing everything completely wrong, let me know. The approach in the link I gave seemed simpler then implementing an entire repository pattern. I am just trying to be able to find the easiest way to unit test my code.

You can use FakeDbSet NuGet Package or implement your own InMemoryDbSet<T> class ( InMemoryDbSet<T> that is used in code snippet is the one from FakeDbSet package):

Mock<IDbContext> mockContext = new Mock<IDbContext>();
question TestQuestion = new question { 
    Id = 1,
    ToAsk = "Did this test work?"
};
IDbSet<question> questions = new InMemoryDbSet<question>(true){ TestQuestion };
mockContext.Setup(c => c.EntitySet<question>()).Returns(questions);

QuestionsController controller = new QuestionsController( mockContext.Object );
List<DHT.Entity.Models.question> questions = controller.Get();
Assert.AreEqual(questions.Count, 1);

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