Reputation: 14282
Given the following:
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();
}
}
I'm seeing test data show up in the database. And I'm seeing the following in an error in the test output:
A TransactionScope must be disposed in the same thread that created it.
This occurs only when ALL tests are run. When any given test is run individually, there's no problem.
If I remove the scope.Dispose()
call, allowing the scope to be disposed "naturally", the error vanishes, but I still see records accumulate in the database.
Upvotes: 2
Views: 110
Reputation: 14282
Without speaking too much to how TransactionScope
works with threads (because I'm ignorant on the matter), the problem has been resolved by creating the scopes during the instantiation of each TestClass
.
To save a handful of keystrokes, we created a ScopedTestClass
class:
public class ScopedTestClass : IDisposable
{
private TransactionScope TxnScope;
public ScopedTestClass()
{
TxnScope = new TransactionScope();
}
public void Dispose()
{
TsnScope.Dispose();
}
}
And each TestClass
inherits from that:
[TestClass]
public class MyTestClass : ScopedTestClass
{
[TestMethod]
public void DoSomething()
{
// sanity at last!
}
}
And everything is good.
Upvotes: 2