对于单元测试,我想将现有的数据库和数据复制到内存数据库中,以免影响真实数据。
我使用 SQL Server、ASP.NET Core、Entity Framework Core 和 Xunit 进行测试。
怎么做?
要将数据从现有的 SQL Server 数据库导入内存数据库以使用 Xunit、ASP.NET Core 和 Entity Framework Core 进行单元测试,您可以使用 Entity Framework Core 从现有数据库中提取数据并将其插入到内存数据库。
步骤如下:
这是实现此目的的代码示例:
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 !
}