如何在单元测试之间重置EF7 InMemory提供程序?

编程入门 行业动态 更新时间:2024-10-18 12:24:45
本文介绍了如何在单元测试之间重置EF7 InMemory提供程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试使用EF7 InMemory提供程序进行单元测试,但是两次测试之间InMemory数据库的持久性导致我遇到问题.

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.

以下代码演示了我的问题.一个测试将起作用,而另一个测试将始终失败.即使我在两次测试之间将_context设置为null,第二次测试运行仍将始终包含4条记录.

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.

[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; } }

推荐答案

以下调用将清除内存中的数据存储.

The following call will clear the in-memory datastore.

_context.Database.EnsureDeleted();

更多推荐

如何在单元测试之间重置EF7 InMemory提供程序?

本文发布于:2023-11-14 09:42:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1586871.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:单元测试   程序   如何在   InMemory

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!