.net核心模拟dbcontext无法正常工作(静态问题?)

时间:2019-02-07 21:24:19

标签: c# testing .net-core moq xunit

我正在尝试测试.net core 2.2 api。我在模拟(使用最小起订量)dbcontext时遇到困难。使我的mockDbContext可用的语法是什么?我收到一个NullReferenceException。由于Changetracker从未实例化,我相信。我需要其他方法吗?我看到提到了.UseInMemoryDatabase(),但是文档很少或没有很好的示例。

下面是我要在测试[事实]中使用的代码。

     var mockDbContext = new Mock<dbContext>(optionsBuilder.Options);
     var controller = new HomeController(mockDbContext.object);

然后使用控制器进行测试...为简洁起见

var datafromdbcontext = controller.GetData();

下面是我的dbcontext的示例。

    public class dbContext:DbContext
    {
        public dbContext(DbContextOptions<dbContext> options)
        : base(options)
        {
            //MAKE IT READONLY
            ChangeTracker.QueryTrackingBehavior = 
       QueryTrackingBehavior.NoTracking;
        }

2 个答案:

答案 0 :(得分:2)

有很多使用InMemory数据库的示例(通常用于单元测试)……这是一个示例:https://docs.microsoft.com/en-us/ef/core/miscellaneous/testing/in-memory

您不应尝试模拟实际上下文,而应使用InMemory选项。所以-您的上下文,但是带有InMemory“ option” ...就像这样:

var myFakeContext = new DbContextOptionsBuilder<MYDBCONTEXT>().UseInMemoryDatabase("SO-MADE-UP-NAME"); 

答案 1 :(得分:0)

我创建了一个库,在NuGet和GitHub上可用,名为EntityFrameworkCoreMock,它可以很轻松地完成所有设置。 Moq也有一个实现。

https://github.com/huysentruitw/entity-framework-core-mock

用法示例

public class User
{
    [Key, Column(Order = 0)]
    public Guid Id { get; set; }

    public string FullName { get; set; }
}

public class TestDbContext : DbContext
{
    public TestDbContext(DbContextOptions<TestDbContext> options)
        : base(options)
    {
    }

    public virtual DbSet<User> Users { get; set; }
}

public class MyTests
{
    [Fact]
    public void Test()
    {
        var initialEntities = new[]
        {
            new User { Id = Guid.NewGuid(), FullName = "Eric Cartoon" },
            new User { Id = Guid.NewGuid(), FullName = "Billy Jewel" },
        };

        var dbContextMock = new DbContextMock<TestDbContext>(DummyOptions);
        var usersDbSetMock = dbContextMock.CreateDbSetMock(x => x.Users, initialEntities);

        // Pass dbContextMock.Object to the class/method you want to test

        // Query dbContextMock.Object.Users to see if certain users were added or removed
        // or use Mock Verify functionality to verify if certain methods were called: usersDbSetMock.Verify(x => x.Add(...), Times.Once);
   }

    public DbContextOptions<TestDbContext> DummyOptions { get; } = new DbContextOptionsBuilder<TestDbContext>().Options;
}