I faced an interesting problem today when writing some code that was dealing with transactions. Basically, I had a method that created a TransactionScope and did some stuff before completing it. I wanted to write a test to verify that the transaction was not being aborted.
The solution was quite simple, actually. By creating my own transaction scope in the test, the one being created by the method I was testing would then become a nested transaction, part of the one I could control. This allowed me to do a simple assert on the the transaction status after calling the method:
[TestMethod]
public void Completes_the_transaction()
{
// By creating a scope here, we make the one AssignSubstitute creates nested within the one we control,
// which allows us to verify that it was committed
using (new TransactionScope())
{
_assigner.AssignSubstitute(_substituteId, _unassignedItemId); // this method creates a TransactionScope
Assert.AreEqual(TransactionStatus.Active,Transaction.Current.TransactionInformation.Status);
}
}
By asserting that the transaction is still active after the nested scope has been polled, I can deduce that Complete was called in it - anything else will cause the Status to change (for example to Aborted).