简体   繁体   English

如何为实体框架模拟接口?

[英]How to mock an interface for entity framework?

I followed the answer here to create a interface for the DbContext in entity framework. 我按照此处的答案在实体框架中为DbContext创建接口。 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. 一个没有参数,并将IDbContext实例变量设置为新的DbContext。 The other takes an IDbContext and sets the same instance variable. 另一个采用IDbContext并设置相同的实例变量。 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. 以下是我使用Moq并测试控制器的失败尝试。 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. 我对.NET和C#还是很陌生,所以如果我做的所有事情都完全错误,请告诉我。 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): 您可以使用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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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