鉴于以下情况:
public class TestEnvironment
{
private static TransactionScope scope;
[AssemblyInitialize]
public static void Init(TestContext context)
{
/* establish database connection, create Session fake, create Items fake, etc. */
scope = new TransactionScope();
}
[AssemblyCleanup]
public static void Cleanup()
{
scope.Dispose();
}
}
我看到测试数据显示在数据库中。我在测试输出中看到以下错误:
A TransactionScope must be disposed in the same thread that created it.
仅当运行所有测试时才会发生这种情况。当任何给定的测试单独运行时,没有问题。
如果我删除 scope.Dispose()
调用,允许“自然”处理作用域,错误就会消失,但我仍然看到数据库中积累了记录。
最佳答案
无需过多讨论 TransactionScope
如何与线程配合使用(因为我对此事一无所知),问题已通过在每个 TestClass< 实例化期间创建范围来解决
.
为了节省少量击键,我们创建了一个 ScopedTestClass
类:
public class ScopedTestClass : IDisposable
{
private TransactionScope TxnScope;
public ScopedTestClass()
{
TxnScope = new TransactionScope();
}
public void Dispose()
{
TsnScope.Dispose();
}
}
每个 TestClass
都继承自:
[TestClass]
public class MyTestClass : ScopedTestClass
{
[TestMethod]
public void DoSomething()
{
// sanity at last!
}
}
一切都很好。
关于c# - 为什么我的 TransactionScope 在测试期间没有得到尊重?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25532299/