如何在單元測試之間重置 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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章