我正在尝试使用EF7 InMemory提供程序进行单元测试,但测试之间InMemory数据库的持久性使我遇到问题。
以下代码演示了我的问题。一个测试将起作用,另一个测试将始终失败。即使我在测试之间将_context设置为null,第二次测试运行也总是有4条记录。
[TestClass]
public class UnitTest1
{
private SchoolContext _context;
[TestInitialize]
public void Setup()
{
Random rng = new Random();
var optionsBuilder = new DbContextOptionsBuilder<SchoolContext>();
optionsBuilder.UseInMemoryDatabase();
_context = new SchoolContext(optionsBuilder.Options);
_context.Students.AddRange(
new Student { Id = rng.Next(1,10000), Name = "Able" },
new Student { Id = rng.Next(1,10000), Name = "Bob" }
);
_context.SaveChanges();
}
[TestCleanup]
public void Cleanup()
{
_context = null;
}
[TestMethod]
public void TestMethod1()
{
Assert.AreEqual(2, _context.Students.ToList().Count());
}
[TestMethod]
public void TestMethod2()
{
Assert.AreEqual(2, _context.Students.ToList().Count());
}
}
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
}
public class SchoolContext : DbContext
{
public SchoolContext(DbContextOptions options) : base(options) { }
public DbSet<Student> Students { get; set; }
}
答案 0 :(得分:61)
以下调用将清除内存中的数据存储区。
_context.Database.EnsureDeleted();
答案 1 :(得分:14)
有点迟到了,但我也遇到了同样的问题,但我最终做的是。
为每个测试指定不同的数据库名称。
@IBAction func backButtonAction(_ sender: Any) {
self.presentingViewController?.dismiss(animated: true, completion: nil)
}
这样你就不必添加
optionsBuilder.UseInMemoryDatabase(Guid.NewGuid().ToString());
在所有测试中
答案 2 :(得分:2)
我使用如下的DbContext
灯具
public class DbContextFixture
where TDbContext : DbContext
{
private readonly DbContextOptions _dbContextOptions =
new DbContextOptionsBuilder()
.UseInMemoryDatabase("_", new InMemoryDatabaseRoot())
.Options;
public TDbContext CreateDbContext()
{
return (TDbContext)(typeof(TDbContext)
.GetConstructor(new[] { typeof(DbContextOptions) })
.Invoke(new[] { _dbContextOptions }));
}
}
您现在可以轻松完成
public class MyRepositoryTests : IDisposable {
private SchoolContext _context;
private DbContextFixture<ApplicationDbContext> _dbContextFixture;
[TestInitialize]
public void Setup() {
_dbContextFixture = new DbContextFixture<ApplicationDbContext>();
_context = _dbContextFixture.CreateDbContext();
_context.Students.AddRange(
new Student { Id = rng.Next(1,10000), Name = "Able" },
new Student { Id = rng.Next(1,10000), Name = "Bob" }
);
_context.SaveChanges();
}
[TestCleanup]
public void Cleanup()
_context.Dispose();
_dbContextFixture = null;
}
[TestMethod]
public void TestMethod1()
{
Assert.AreEqual(2, _context.Students.ToList().Count());
}
[TestMethod]
public void TestMethod2()
{
Assert.AreEqual(2, _context.Students.ToList().Count());
}
}
此解决方案是线程安全的。有关详细信息,请参见我的blog。
答案 3 :(得分:0)
我会结合两个答案。如果并行运行测试,则可能在运行另一个测试的过程中删除了一个数据库,因此在运行30多个测试时,我会看到偶发的故障。
给它一个随机的数据库名称,并确保在测试完成后将其删除。
public class MyRepositoryTests : IDisposable {
private SchoolContext _context;
[TestInitialize]
public void Setup() {
var options = new DbContextOptionsBuilder<ApplicationDbContext>()
// Generate a random db name
.UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
.Options;
_context = new ApplicationDbContext(options);
}
[TestCleanup]
public void Cleanup()
_context.Database.EnsureDeleted(); // Remove from memory
_context.Dispose();
}
}
答案 4 :(得分:0)
只需将您的DbContextOptionsBuilder代码定义更改如下:
var databaseName = "DatabaseNameHere";
var dbContextOption = new DbContextOptionsBuilder<SchoolContext>()
.UseInMemoryDatabase(databaseName, new InMemoryDatabaseRoot())
.Options;
新的InMemoryDatabaseRoot()正在创建新的数据库,而ID不再存在。 因此,您现在不需要:
[TestCleanup]
public void Cleanup()
{
_context = null;
}
答案 5 :(得分:0)
此处的示例通过RemoveRange实现此目的:https://docs.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-3.1
db.<Entity>.RemoveRange(db.<entity>);
答案 6 :(得分:0)
这是我的2分方法,可以使每个单元测试彼此隔离。我正在使用C#7,XUnit和EF core 3.1。
示例TestFixture类。
public class SampleIntegrationTestFixture : IDisposable
{
public DbContextOptionsBuilder<SampleDbContext> SetupInMemoryDatabase()
=> new DbContextOptionsBuilder<SampleDbContext>().UseInMemoryDatabase("MyInMemoryDatabase");
private IEnumerable<Student> CreateStudentStub()
=> new List<Student>
{
new Student { Id = rng.Next(1,10000), Name = "Able" },
new Student { Id = rng.Next(1,10000), Name = "Bob" }
};
public void Dispose()
{
}
}
示例IntegrationTest类
public class SampleJobIntegrationTest : IClassFixture<SampleIntegrationTestFixture >
{
private DbContextOptionsBuilder<SampleDbContext> DbContextBuilder { get; }
private SampleDbContext SampleDbContext { get; set; }
public SampleJobIntegrationTest(SampleIntegrationTestFixture
sampleIntegrationTestFixture )
{
SampleIntegrationTestFixture = sampleIntegrationTestFixture ;
SampleDbContextBuilder = sampleIntegrationTestFixture .SetupInMemoryDatabase();
}
[Fact]
public void TestMethod1()
{
using(SampleDbContext = new SampleDbContext(SampleDbContextBuilder.Options))
var students= SampleIntegrationTestFixture.CreateStudentStub();
{
SampleDbContext.Students.AddRange(students);
SampleDbContext.SaveChanges();
Assert.AreEqual(2, _context.Students.ToList().Count());
SampleDbContext.Database.EnsureDeleted();
}
}