Jax*_*ian 6 c# unit-testing entity-framework transactions vs-unit-testing-framework
在我关于在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
}
}
Run Code Online (Sandbox Code Playgroud)
Shi*_*iji 10
我们使用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();
}
Run Code Online (Sandbox Code Playgroud)
这将回滚在任何测试中所做的任何更改.