如何针对每个XUnit测试隔离EF InMemory数据库

47

我正在尝试在我的xunit存储库测试中使用InMemory EF7数据库。

但我的问题是,当我尝试Dispose创建的上下文时,内存中的数据库会持续存在。这意味着一个测试会影响其他测试。

我已经阅读了这篇文章Unit Testing Entity Framework 7 with the In Memory Data Store,并尝试在我的TestClass的构造函数中设置上下文。但这种方法不起作用。当我单独运行测试时,一切都正常,但我的第一个测试方法向数据库添加了一些东西,第二个测试方法从上一个测试方法的脏数据库开始。我试图将IDispose添加到测试类中,但DatabaseContext方法和DB仍然保留在内存中。我做错了什么,我漏掉了什么?

我的代码如下:

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;

namespace Fabric.Tests.Repositories
{
    /// <summary>
    /// Test for TaskRepository 
    /// </summary>
    public class TaskRepositoryTests:IDisposable
    {

        private readonly DatabaseContext contextMemory;

        /// <summary>
        /// Constructor
        /// </summary>
        public TaskRepositoryTests()
        {
            var optionsBuilder = new DbContextOptionsBuilder<DatabaseContext>();
            optionsBuilder.UseInMemoryDatabase();
            contextMemory = new DatabaseContext(optionsBuilder.Options);

        }

        /// <summary>
        /// Dispose DB 
        /// </summary>
        public void Dispose()
        {
            //this has no effect 
            if (contextMemory != null)
            {                
                contextMemory.Dispose();
            }
        }


        /// <summary>
        /// Positive Test for ListByAssigneeId method  
        /// </summary>
        /// <returns></returns>       
        [Fact]
        public async Task TasksRepositoryListByAssigneeId()
        {
            // Arrange
            var assigneeId = Guid.NewGuid();
            var taskList = new List<TaskItem>();


            //AssigneeId != assigneeId 
            taskList.Add(new TaskItem()
            {
                AssigneeId = Guid.NewGuid(),
                CreatorId = Guid.NewGuid(),
                Description = "Descr 2",
                Done = false,
                Id = Guid.NewGuid(),
                Location = "Some location 2",
                Title = "Some title 2"
            });

            taskList.Add(new TaskItem()
            {
                AssigneeId = assigneeId,
                CreatorId = Guid.NewGuid(),
                Description = "Descr",
                Done = false,
                Id = Guid.NewGuid(),
                Location = "Some location",
                Title = "Some title"
            });

            taskList.Add(new TaskItem()
            {
                AssigneeId = assigneeId,
                CreatorId = Guid.NewGuid(),
                Description = "Descr 2",
                Done = false,
                Id = Guid.NewGuid(),
                Location = "Some location 2",
                Title = "Some title 2"
            });

            //AssigneeId != assigneeId 
            taskList.Add(new TaskItem()
            {
                AssigneeId = Guid.NewGuid(),
                CreatorId = Guid.NewGuid(),
                Description = "Descr 2",
                Done = false,
                Id = Guid.NewGuid(),
                Location = "Some location 2",
                Title = "Some title 2"
            });


            //set up inmemory DB            
            contextMemory.TaskItems.AddRange(taskList);

            //save context
            contextMemory.SaveChanges();

            // Act
            var repository = new TaskRepository(contextMemory);
            var result = await repository.ListByAssigneeIdAsync(assigneeId);

            // Assert
            Assert.NotNull(result.Count());

            foreach (var td in result)
            {
                Assert.Equal(assigneeId, td.AssigneeId);
            }

        }

        /// <summary>
        /// test for Add method  
        /// (Skip = "not able to clear DB context yet")
        /// </summary>
        /// <returns></returns>
        [Fact]
        public async Task TasksRepositoryAdd()
        {
            var item = new TaskData()
            {
                AssigneeId = Guid.NewGuid(),
                CreatorId = Guid.NewGuid(),
                Description = "Descr",
                Done = false,
                Location = "Location",
                Title = "Title"
            };


            // Act
            var repository = new TaskRepository(contextMemory);
            var result = await repository.Add(item);

            // Assert
            Assert.Equal(1, contextMemory.TaskItems.Count());
            Assert.NotNull(result.Id);

            var dbRes = contextMemory.TaskItems.Where(s => s.Id == result.Id).SingleOrDefault();
            Assert.NotNull(dbRes);
            Assert.Equal(result.Id, dbRes.Id);
        }


    }
}

我正在使用:

"Microsoft.EntityFrameworkCore.InMemory": "1.0.0"

"Microsoft.EntityFrameworkCore": "1.0.0"

"xunit": "2.2.0-beta2-build3300"

2
你可以为每个测试命名你的数据库。 在这里看看我的回答 https://dev59.com/YZPfa4cB1Zd3GeqPA0Jr#38727634 - Yuriy Granovskiy
谢谢你的回答,这个方法可能可行...我会试一下! - Ivan Mjartan
{btsdaf} - Jeremy Thompson
2个回答

55

根据文档,通常情况下,EF为同一类型的所有上下文在AppDomain中创建一个单独的IServiceProvider实例,这意味着所有上下文实例都共享同一个内存数据库实例。通过允许传递一个实例,您可以控制内存数据库的范围。

不要将测试类设为可释放并尝试以此方式处理数据上下文的释放,而是为每个测试创建一个新的上下文:

private static DbContextOptions<BloggingContext> CreateNewContextOptions()
{
    // Create a fresh service provider, and therefore a fresh 
    // InMemory database instance.
    var serviceProvider = new ServiceCollection()
        .AddEntityFrameworkInMemoryDatabase()
        .BuildServiceProvider();

    // Create a new options instance telling the context to use an
    // InMemory database and the new service provider.
    var builder = new DbContextOptionsBuilder<DatabaseContext>();
    builder.UseInMemoryDatabase()
           .UseInternalServiceProvider(serviceProvider);

    return builder.Options;
}

然后,在每个测试中,使用这种方法新建一个数据上下文:

using (var context = new DatabaseContext(CreateNewContextOptions()))
{
    // Do all of your data access and assertions in here
}

这种方法应该能让你为每个测试获得一个崭新的内存数据库。


1
嗨Nate,在最新版本中,约束已被移除。但无论如何,在我的存储库中,我仍然在SvaeChanges之前使用验证System.ComponentModel.DataAnnotations,并且它对我很有效。 :-) - Ivan Mjartan
1
拯救了我的生命。谢谢! - starmandeluxe
3
@NateBarbettini 太棒了,这个方法完美地解决了我的问题!但我还是有点困惑,为什么一定要这样做。难道每次指定一个新的数据库名称不就可以了吗?我现在是用的.UseInMemoryDatabase(Guid.NewGuid().ToString()),但仍然存在共享的情况。 - MEMark
@MEMark 我也不太确定。我和你一样认为,但似乎内存数据库在后台的行为就像单例模式。也许有一个很好的解释,但我不确定。 - Nate Barbettini
1
@MEMark 好久不见,你看到这个了吗?https://github.com/aspnet/EntityFrameworkCore/issues/6872 - IEnjoyEatingVegetables
显示剩余6条评论

17

我认为Nate给出的答案现在可能已经过时了,或者我做错了什么。 UseInMemoryDatabase()现在需要一个数据库名称。

以下是我最终的结果。我添加了一行来创建一个唯一的数据库名称。 我删除了using语句,改用只调用一次的构造函数和释放函数。

里面有一些我的测试调试代码。

public class DeviceRepositoryTests : IClassFixture<DatabaseFixture>, IDisposable
{

    private readonly DeviceDbContext _dbContext;
    private readonly DeviceRepository _repository;

    private readonly ITestOutputHelper _output;
    DatabaseFixture _dbFixture;

    public DeviceRepositoryTests(DatabaseFixture dbFixture, ITestOutputHelper output)
    {
        this._dbFixture = dbFixture;
        this._output = output;

        var dbOptBuilder = GetDbOptionsBuilder();
        this._dbContext = new DeviceDbContext(dbOptBuilder.Options);
        this._repository = new DeviceRepository(_dbContext);

        DeviceDbContextSeed.EnsureSeedDataForContext(_dbContext);
        //_output.WriteLine($"Database: {_dbContext.Database.GetDbConnection().Database}\n" +
        _output.WriteLine($"" +
              $"Locations: {_dbContext.Locations.Count()} \n" +
              $"Devices: {_dbContext.Devices.Count()} \n" +
              $"Device Types: {_dbContext.DeviceTypes.Count()} \n\n");

        //_output.WriteLine(deviceDbContextToString(_dbContext));
    }

    public void Dispose()
    {
        _output.WriteLine($"" +
                          $"Locations: {_dbContext.Locations.Count()} \n" +
                          $"Devices: {_dbContext.Devices.Count()} \n" +
                          $"Device Types: {_dbContext.DeviceTypes.Count()} \n\n");
        _dbContext.Dispose();
    }

    private static DbContextOptionsBuilder<DeviceDbContext> GetDbOptionsBuilder()
    {

        // The key to keeping the databases unique and not shared is 
        // generating a unique db name for each.
        string dbName = Guid.NewGuid().ToString();

        // Create a fresh service provider, and therefore a fresh 
        // InMemory database instance.
        var serviceProvider = new ServiceCollection()
            .AddEntityFrameworkInMemoryDatabase()
            .BuildServiceProvider();

        // Create a new options instance telling the context to use an
        // InMemory database and the new service provider.
        var builder = new DbContextOptionsBuilder<DeviceDbContext>();
        builder.UseInMemoryDatabase(dbName)
               .UseInternalServiceProvider(serviceProvider);

        return builder;
    }

这是一个非常基础的测试案例。

[Fact]
public void LocationExists_True()
{
    Assert.True(_repository.LocationExists(_dbFixture.GoodLocationId));
}

我还制作了8个测试用例,试图删除具有相同id的同一设备,并且每个测试用例都通过了。


1
它运行得非常完美。如果有人知道内存中数据库的生命周期,分享一下就太好了! - Pawel Wujczyk
唯一的数据库是否保存在临时文件中?我尝试关闭进程并重新打开,但数据仍然存在。如果每次都创建一个新文件,这是否是良好的工程实践? - Soundararajan
1
谢谢您,这是我在大量搜索后找到的最好、最简单的解决方案! - Avrohom Yisroel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接