我已将Web应用程序项目从.NET Core 2.1迁移到3.1(也将EF Core从2.1.1迁移到3.1.0)。
迁移后,某些单元测试不再起作用,抛出重复键db异常。
我模拟了这个问题,并意识到带有选项UseInmemoryDatabase
的EF内核在3.1中的行为有所不同,它不会清除旧数据。
在第二种测试方法中,People
表已经包含从第一次测试中添加的数据,而在2.1中则没有发生
有人知道我如何使内存数据库成为每个单元测试的范围吗?
这是我的测试代码:
AppDbContext.cs
using microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
namespace MyConsoleApp.Database
{
public class AppDbContext: DbContext
{
protected AppDbContext(DbContextOptions options) : base(options) { }
public AppDbContext(DbContextOptions<AppDbContext> options) : this((DbContextOptions)options)
{
}
public virtual DbSet<Person> Person { get; set; }
}
public class Person
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
}
}
AppUnitTest.cs
using microsoft.EntityFrameworkCore;
using microsoft.Extensions.DependencyInjection;
using microsoft.VisualStudio.TestTools.UnitTesting;
using MyConsoleApp.Database;
using System.Linq;
namespace MyConsoleAppTest
{
[TestClass]
public class AppUnitTest
{
public ServiceCollection Services { get; private set; }
public ServiceProvider ServiceProvider { get; protected set; }
[TestInitialize]
public void Initialize()
{
Services = new ServiceCollection();
Services.AddDbContext<AppDbContext>(opt => opt.UseInmemoryDatabase(databaseName: "InmemoryDb"),ServiceLifetime.Scoped,ServiceLifetime.Scoped);
ServiceProvider = Services.BuildServiceProvider();
}
[TestMethod]
public void TestMethod1()
{
using (var dbContext = ServiceProvider.GetService<AppDbContext>())
{
dbContext.Person.Add(new Person { Id = 0,Name = "test1" });
dbContext.SaveChanges();
Assert.IsTrue(dbContext.Person.Count() == 1);
}
}
[TestMethod]
public void TestMethod2()
{
using (var dbContext = ServiceProvider.GetService<AppDbContext>())
{
dbContext.Person.Add(new Person { Id = 0,Name = "test2" });
dbContext.SaveChanges();
Assert.IsTrue(dbContext.Person.Count() == 1);
}
}
[TestCleanup]
public virtual void Cleanup()
{
ServiceProvider.Dispose();
ServiceProvider = null;
}
}
}
MyConsoleAppTest.csproj
<Project Sdk="microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="microsoft.EntityFrameworkCore.Inmemory" Version="3.1.0" />
<PackageReference Include="microsoft.NET.Test.Sdk" Version="16.2.0" />
<PackageReference Include="MSTest.TestAdapter" Version="2.0.0" />
<PackageReference Include="MSTest.TestFramework" Version="2.0.0" />
<PackageReference Include="coverlet.collector" Version="1.0.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\MyConsoleApp\MyConsoleApp.csproj" />
</ItemGroup>
</Project>