在事务中包装可视化工作室数据库单元测试以消除持久存在的数据库更改

时间:2015-11-04 17:12:54

标签: database unit-testing sql-server-2012 visual-studio-2015

我正在使用VS 2015单元测试来获取SQL Server 2012数据库。我希望能够使用预测试来插入测试数据并将整个单元测试包装在一个事务中,该事务可以在测试结束时回滚。我已经尝试在TransactionScope(下面)中包装整个测试代码,但它不会回滚插入。

            using (TransactionScope scope = new TransactionScope())
        {
            SqlDatabaseTestActions testActions = this.dbo_Proc1TestData;
            // Execute the pre-test script
            // 
            System.Diagnostics.Trace.WriteLineIf((testActions.PretestAction != null), "Executing pre-test script...");
            SqlExecutionResult[] pretestResults = TestService.Execute(this.PrivilegedContext, this.PrivilegedContext, testActions.PretestAction);
            try
            {
                // Execute the test script
                // 
                System.Diagnostics.Trace.WriteLineIf((testActions.TestAction != null), "Executing test script...");
                SqlExecutionResult[] testResults = TestService.Execute(this.ExecutionContext, this.PrivilegedContext, testActions.TestAction);
            }
            finally
            {
                // Execute the post-test script
                // 
                System.Diagnostics.Trace.WriteLineIf((testActions.PosttestAction != null), "Executing post-test script...");
                SqlExecutionResult[] posttestResults = TestService.Execute(this.PrivilegedContext, this.PrivilegedContext, testActions.PosttestAction);
            }
        }

有没有其他方法可以实现这一点而无需在测试后删除数据?

1 个答案:

答案 0 :(得分:1)

事实证明,ExecutionContext和PrivilegedContext已经创建,因此不会在TransactionScope创建的事务中登记。修复是为using语句中的每个上下文添加对EnlistTransaction的调用:

        using (TransactionScope scope = new TransactionScope(TransactionScopeOption.RequiresNew))
        {
            this.ExecutionContext.Connection.EnlistTransaction(Transaction.Current);
            this.PrivilegedContext.Connection.EnlistTransaction(Transaction.Current);