gpt4 book ai didi

c# - 为什么我的 TransactionScopes 在测试期间没有得到尊重?

转载 作者:太空宇宙 更新时间:2023-11-03 10:40:24 25 4
gpt4 key购买 nike

鉴于以下情况:

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# - 为什么我的 TransactionScopes 在测试期间没有得到尊重?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25532299/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com