c# – 如何在EF4中回滚单元测试TearDown?
发布时间:2020-12-15 04:34:16 所属栏目:百科 来源:网络整理
导读:在我关于在EF4中回滚交易的研究中,似乎每个人都提到了 this blog post或提供了类似的解释.在我的场景中,我想在单元测试场景中执行此操作,我想在我的单元测试上下文中回滚几乎我所做的一切,以防止更新数据库中的数据(是的,我们会增加计数器但是没关系).为了做
在我关于在EF4中回滚交易的研究中,似乎每个人都提到了
this blog post或提供了类似的解释.在我的场景中,我想在单元测试场景中执行此操作,我想在我的单元测试上下文中回滚几乎我所做的一切,以防止更新数据库中的数据(是的,我们会增加计数器但是没关系).为了做到这一点,最好遵循以下计划吗?我错过了一些概念或其他任何重要的概念(除了我的SetupMyTest和PerformMyTest函数不会真的存在这种方式)?
[TestMethod] public void Foo { using (var ts = new TransactionScope()) { // Arrange SetupMyTest(context); // Act PerformMyTest(context); var numberOfChanges = context.SaveChanges(SaveOptions.AcceptAllChangesAfterSave); // if there's an issue,chances are that an exception has been thrown by now. // Assert Assert.IsTrue(numberOfChanges > 0,"Failed to _____"); // transaction will rollback because we do not ever call Complete on it } } 解决方法
我们使用TransactionScope.
private TransactionScope transScope; #region Additional test attributes // // Use TestInitialize to run code before running each test [TestInitialize()] public void MyTestInitialize() { transScope = new TransactionScope(); } // Use TestCleanup to run code after each test has run [TestCleanup()] public void MyTestCleanup() { transScope.Dispose(); } 这将回滚在任何测试中所做的任何更改. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |