title: Unit Testing the Use of TransactionScope
body: <p><strong>The preamble:</strong>
  I have designed a strongly interfaced and fully mockable data layer class that expects the business layer to create a <a href="http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope.aspx?ppud=4" rel="noreferrer"><code>TransactionScope</code></a> when multiple calls should be included in a single transaction. </p>
  
  <p><strong>The problem:</strong> I would like to unit test that my business layer makes use of a <code>TransactionScope</code> object when I expect it to. </p>
  
  <p>Unfortunately, the standard pattern for using <code>TransactionScope</code> is a follows:</p>
  
  <pre><code>using(var scope = new TransactionScope())
  {
      // transactional methods
      datalayer.InsertFoo();
      datalayer.InsertBar();
      scope.Complete();
  }
  </code></pre>
  
  <p>While this is a really great pattern in terms of usability for the programmer, testing that it's done seems... unpossible to me. I cannot detect that a transient object has been instantiated, let alone mock it to determine that a method was called on it. Yet my goal for coverage implies that I must. </p>
  
  <p><strong>The Question:</strong> How can I go about building unit tests that ensure <code>TransactionScope</code> is used appropriately according to the standard pattern?</p>
  
  <p><strong>Final Thoughts:</strong> I've considered a solution that would certainly provide the coverage I need, but have rejected it as overly complex and not conforming to the standard <code>TransactionScope</code> pattern. It involves adding a <code>CreateTransactionScope</code> method on my data layer object that returns an instance of <code>TransactionScope</code>. But because TransactionScope contains constructor logic and non-virtual methods and is therefore difficult if not impossible to mock, <code>CreateTransactionScope</code> would return an instance of <code>DataLayerTransactionScope</code> which would be a mockable facade into <code>TransactionScope</code>. </p>
  
  <p>While this might do the job it's complex and I would prefer to use the standard pattern. Is there a better way?</p>