在我关于在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(); }
这将回滚在任何测试中所做的任何更改.
原文地址:https://www.jb51.cc/csharp/91225.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。