2

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.

4

1 回答 1

0

您可以使用 FakeDbSet NuGet 包或实现自己的InMemoryDbSet<T>类(InMemoryDbSet<T>代码片段中使用的是 FakeDbSet 包中的类):

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);
于 2013-11-13T15:13:58.613 回答