如何在单元测试之间重置 EF7 InMemory 提供程序? - How can I reset an EF7 InMemory provider between unit tests?

问题:

I am trying to use the EF7 InMemory provider for unit tests, but the persistent nature of the InMemory database between tests is causing me problems.我正在尝试使用 EF7 InMemory 提供程序进行单元测试,但 InMemory 数据库在测试之间的持久性给我带来了问题。

The following code demonstrates my issue.以下代码演示了我的问题。 One test will work and the other test will always fail.一个测试会成功,而另一个测试总是失败。 Even though I set the _context to null between tests, the second test run will always have 4 records in it.即使我在测试之间将_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; }
}

解决方案:

参考: https://stackoom.com/en/question/2GWSW
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章