简体   繁体   English

.net内核中的魔清DI-ed DbContext

[英]Moqing DI-ed DbContext in .net core

I started writing tests for a (webapi) application in .net core using ef core.我开始使用 ef 核心在 .net 核心中为(webapi)应用程序编写测试。 The repositories I want to test look like this:我要测试的存储库如下所示:

   public class MyRepository : IMyRepository
   {
   private readonly IDbContext Db;
   public MyReporitory(IDbContext db) 
      {
         Db = db;
      }
   /// Methods to access the Database
      public List<MyType> Get() {
         return Db.Set<Type>();
      }

In my test I now try to mock the DBContext:在我的测试中,我现在尝试模拟 DBContext:

 var dbContextMock = new Mock<IDBContext>();
 var classToBeTested = new MyRepository(dbContextMock)
 var result = classToBeTested.Get() (or any other method in my repository);
 Assert.That(result, Is.TypeOf<MyType>)

When I run the test I get a null exception since the returned result is null (and I didnt tell the mock how to return data?) How would I add data to the mocked DbContext so the Get() can get it?当我运行测试时,我得到一个 null 异常,因为返回的结果是 null (我没有告诉模拟如何返回数据?)我如何将数据添加到模拟的 DbContext 以便 Get() 可以得到它?

Use moq setup to return data.使用最小起订量设置返回数据。 If I am correct you have created an Set method in your interface.如果我是正确的,你已经在你的界面中创建了一个 Set 方法。 Just mock that method只是嘲笑那个方法

If your set method returns an DbSet type then you can mock it with this bit of code如果您的 set 方法返回 DbSet 类型,那么您可以使用这段代码来模拟它

        var mockDbSet = new Mock<DbSet<TestClass>>();
        mockDbSet.As<IQueryable<TestClass>>().Setup(m => m.Provider).Returns(data.Provider);
        mockDbSet.As<IQueryable<TestClass>>().Setup(m => m.Expression).Returns(data.Expression);
        mockDbSet.As<IQueryable<TestClass>>().Setup(m => m.ElementType).Returns(data.ElementType);
        mockDbSet.As<IQueryable<TestClass>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator);

data is of an type IQueryable数据属于 IQueryable 类型

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

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