Unit Testing the Use of TransactionScope

后端 未结 5 1238
情书的邮戳
情书的邮戳 2021-01-31 09:35

The preamble: I have designed a strongly interfaced and fully mockable data layer class that expects the business layer to create a TransactionScope when multip

5条回答
  •  深忆病人
    2021-01-31 09:47

    After having thought through the same issue myself, I came to the following solution.

    Change the pattern to:

    using(var scope = GetTransactionScope())
    {
        // transactional methods
        datalayer.InsertFoo();
        datalayer.InsertBar();
        scope.Complete();
    }
    
    protected virtual TransactionScope GetTransactionScope()
    {
        return new TransactionScope();
    }
    

    When you then need to test your code, you inherit the Class under test, extending the function, so you can detect if it was invoked.

    public class TestableBLLClass : BLLClass
        {
            public bool scopeCalled;
    
            protected override TransactionScope GetTransactionScope()
            {
                this.scopeCalled = true;
                return base.GetTransactionScope();
            }
        }
    

    You then perform the tests relating to TransactionScope on the testable version of your class.

提交回复
热议问题