如何在 EF4 中回滚进行单元测试拆卸?
在我关于 EF4 中回滚事务的研究中,似乎每个人都提到 这篇博文或提供了类似的解释。在我的场景中,我想在单元测试场景中执行此操作,在该场景中我想回滚我在单元测试上下文中所做的几乎所有操作,以防止更新数据库中的数据(是的,我们将增加计数器,但这没关系)。为了做到这一点,最好遵循以下计划吗?我是否缺少一些概念或其他主要内容(除了我的 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
}
}
In my research about rolling back transactions in EF4, it seems everybody refers to this blog post or offers a similar explanation. In my scenario, I'm wanting to do this in a unit testing scenario where I want to rollback practically everything I do within my unit testing context to keep from updating the data in the database (yeah, we'll increment counters but that's okay). In order to do this, is it best to follow the following plan? Am I missing some concept or anything else major with this (aside from my SetupMyTest
and PerformMyTest
functions won't really exist that way)?
[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
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我们为此使用 TransactionScope。
这将回滚任何测试中所做的任何更改。
We use TransactionScope for this.
This will rollback any changes made in any of the tests.