如何将包含数据的现有数据库复制到内存数据库中,以便使用 Xunit 和 ASP.NET Core 以及 Entity Framework Core 进行单元测试?

问题描述 投票:0回答:1

对于单元测试,我想将现有的数据库和数据复制到内存数据库中,以免影响真实数据。

我使用 SQL Server、ASP.NET Core、Entity Framework Core 和 Xunit 进行测试。

怎么做?

sql-server asp.net-core entity-framework-core xunit in-memory-database
1个回答
0
投票

要将数据从现有的 SQL Server 数据库导入内存数据库以使用 Xunit、ASP.NET Core 和 Entity Framework Core 进行单元测试,您可以使用 Entity Framework Core 从现有数据库中提取数据并将其插入到内存数据库。

步骤如下:

  1. 使用与现有数据库不同的名称创建一个新的内存数据库。
  2. 添加一个使用现有数据库的新数据库上下文。
  3. 从现有数据库上下文中检索数据。
  4. 将数据插入新的内存数据库。
  5. 在单元测试中使用新的内存数据库。

这是实现此目的的代码示例:

    private readonly MyDbContext _testDbContext;

    public AnyServiceTests()
    {
        // Create a new in-memory database
        var options = new DbContextOptionsBuilder<MyDbContext>()
            .UseInMemoryDatabase(databaseName: "MyTestDatabase")
            .Options;
        
        // Add a new database context that uses the existing database
        var existingDbOptions = new DbContextOptionsBuilder<MyDbContext>()
            .UseSqlServer("connectionStringToExistingDb")
            .Options;
        
        using (var existingDbContext = new MyDbContext(existingDbOptions))
        {
            // Retrieve data from the existing database context
            var dataToImport = existingDbContext.MyTable.ToList();
        
            // Insert the data into the new in-memory database
            _testDbContext = new MyDbContext(options);
            _testDbContext.MyTable.AddRange(dataToImport);
            _testDbContext.SaveChanges();
        }
    }
        
    [Fact]
    public async Task MyTestMethod()
    {
        // Use the new in-memory database to run tests
        var result = _testDbContext.MyTable.Where(x => x...);
        // The real data is not affected !
    }
© www.soinside.com 2019 - 2024. All rights reserved.