Consider the following code:
ExecuteSQL("UPDATE ...");
using (var t = new TransactionScope())
{
ExecuteSQL("UPDATE ...");
if (SomeCondition)
t.Commit();
else
t.Rollback();
}
var result = ExecuteSQL("SELECT ...");
Then we write an auto test using outer TransactionScope to rollback changes after each test:
[TestInitialize]
public override void Initialize()
{
_transaction = new TransactionScope();
}
[TestCleanup]
public override void Cleanup()
{
_transaction.Dispose();
}
It’s not possible to write a correct test for a case when SomeCondition is false. Because nested transaction ROLLBACK rollbacks the whole outer transaction including the first UPDATE statement.
Do you know any workarounds?
No. You can rollback to a savepoint, see Exception Handling and Nested Transactions but that is not the same as what you want.
What is what you’re really trying to achieve? Testing should occur under similar conditions to production. Adding an uber transaction and testing methods in inner transactions is nothing like how the system would behave in production.