方法 : 単一のトランザクションのスコープ内で実行されるデータベース単体テストを作成する

単一のトランザクションのスコープ内で実行されるように、単体テストを変更できます。この方法を採用すると、テストの終了後、テストで行われた変更をロールバックできます。手順を次に示します。

  • BEGIN TRANSACTION および ROLLBACK TRANSACTION を使用する Transact-SQL (T-SQL) テスト スクリプトでトランザクションを作成します。

  • テスト クラスで単一のテスト メソッドのトランザクションを作成します。

  • 指定したテスト クラスですべてのテスト メソッドのトランザクションを作成します。

必要条件

このトピックの一部の手順では、単体テストを行うときにコンピュータ上で分散トランザクション コーディネータ サービスを実行する必要があります。詳細については、このトピックの最後にある手順を参照してください。

T-SQL を使用してトランザクションを作成するには

T-SQL を使用してトランザクションを作成するには

  1. データベース単体テスト デザイナで単体テストを開きます。

  2. トランザクションを作成するスクリプトの種類を指定します。たとえば、事前テスト、テスト、または事後テストを指定できます。

  3. T-SQL エディタで、テスト スクリプトを入力します。

  4. 次の簡単な例に示すように、BEGIN TRANSACTION および ROLLBACK TRANSACTION ステートメントを挿入します。この例では、50 行のデータを含む Northwind データベース テーブルを使用します。

    BEGIN TRANSACTION TestTransaction
    UPDATE "Order Details" set Quantity = Quantity + 10
    IF @@ROWCOUNT!=50
    RAISERROR('Row count does not equal 50',16,1)
    ROLLBACK TRANSACTION TestTransaction
    
    Aa833153.alert_note(ja-jp,VS.90).gifメモ :

    COMMIT TRANSACTION ステートメントの実行後にトランザクションをロールバックすることはできません。

ROLLBACK TRANSACTION とストアド プロシージャおよびトリガの連携の詳細については、Microsoft Web サイトの「ROLLBACK TRANSACTION (Transact-SQL)」を参照してください。

単一のテスト メソッドのトランザクションを作成するには

この例では、TransactionScope の型を使用するときに、アンビエント トランザクションを使用します。既定では、実行接続コンテキストと特権接続コンテキストはアンビエント トランザクションを使用しません。これらの接続はメソッドが実行される前に作成されるためです。SqlConnection には、トランザクションとアクティブな接続を関連付ける EnlistTransaction メソッドがあります。アンビエント トランザクションを作成すると、トランザクション自体が現在のトランザクションとして登録されるため、Current プロパティを通してこのトランザクションにアクセスできます。この例では、アンビエント トランザクションが破棄されると、トランザクションはロールバックされます。単体テスト実行時に行われたすべての変更をコミットするには、Complete メソッドを呼び出す必要があります。

単一のテスト メソッドのトランザクションを作成するには

  1. 単体テストの Visual Basic ファイルまたは C# ファイルを開きます。

  2. 次の Visual Basic のコード例に示すように、事前テスト、テスト、および事後テスト アクションをラップします。

        <TestMethod()> _
        Public Sub dbo_InsertTable1Test()
    
            Using ts as New System.Transactions.TransactionScope( System.Transactions.TransactionScopeOption.Required)
                ExecutionContext.Connection.EnlistTransaction(Transaction.Current)
                PrivilegedContext.Connection.EnlistTransaction(Transaction.Current)
    
                Dim testActions As DatabaseTestActions = Me.dbo_InsertTable1TestData
                'Execute the pre-test script
                '
                System.Diagnostics.Trace.WriteLineIf((Not (testActions.PretestAction) Is Nothing), "Executing pre-test script...")
                Dim pretestResults() As ExecutionResult = TestService.Execute(Me.PrivilegedContext, Me.PrivilegedContext, testActions.PretestAction)
                'Execute the test script
    
                System.Diagnostics.Trace.WriteLineIf((Not (testActions.TestAction) Is Nothing), "Executing test script...")
                Dim testResults() As ExecutionResult = TestService.Execute(ExecutionContext, Me.PrivilegedContext, testActions.TestAction)
    
                'Execute the post-test script
                '
                System.Diagnostics.Trace.WriteLineIf((Not (testActions.PosttestAction) Is Nothing), "Executing post-test script...")
                Dim posttestResults() As ExecutionResult = TestService.Execute(Me.PrivilegedContext, Me.PrivilegedContext, testActions.PosttestAction)
    
                'Because the transaction is not explicitly committed, it
                'is rolled back when the ambient transaction is 
                'disposed.
                'To commit the transaction, remove the comment delimiter
                'from the following statement:
                'ts.Complete()
    
        End Sub
        Private dbo_InsertTable1TestData As DatabaseTestActions
    
    Aa833153.alert_note(ja-jp,VS.90).gifメモ :

    Visual Basic を使用している場合は、Imports Microsoft.VisualStudio.TestTools.UnitTesting、Imports Microsoft.VisualStudio.TeamSystem.Data.UnitTesting、および Imports Microsoft.VisualStudio.TeamSystem.Data.UnitTest.Conditions に加えて、Imports System.Transactions を追加する必要があります。Visual C# を使用している場合は、Microsoft.VisualStudio.TestTools、Microsoft.VisualStudio.TeamSystem.Data.UnitTesting、および Microsoft.VisualStudio.TeamSystem.Data.UnitTesting.Conditions に対する using ステートメントに加えて、using System.Transactions を追加する必要があります。プロジェクトへの参照をそれらのアセンブリに追加する必要もあります。

テスト クラスですべてのテスト メソッドのトランザクションを作成するには

テスト クラスですべてのテスト メソッドのトランザクションを作成するには

  1. 単体テストの Visual Basic ファイルまたは C# ファイルを開きます。

  2. Visual C# のコード例に示すように、TestInitialize でトランザクションを作成し、TestCleanup で破棄します。

    TransactionScope _trans;
    
            [TestInitialize()]
            public void Init()
            {
                _trans = new TransactionScope();
                base.InitializeTest();
            }
    
            [TestCleanup()]
            public void Cleanup()
            {
                base.CleanupTest();
                _trans.Dispose();
            }
    
            [TestMethod()]
            public void TransactedTest()
            {
                DatabaseTestActions testActions = this.DatabaseTestMethod1Data;
                // Execute the pre-test script
                // 
                System.Diagnostics.Trace.WriteLineIf((testActions.PretestAction != null), "Executing pre-test script...");
                ExecutionResult[] pretestResults = TestService.Execute(this.PrivilegedContext, this.PrivilegedContext, testActions.PretestAction);
                // Execute the test script
                // 
                System.Diagnostics.Trace.WriteLineIf((testActions.TestAction != null), "Executing test script...");
                ExecutionResult[] testResults = TestService.Execute(this.ExecutionContext, this.PrivilegedContext, testActions.TestAction);
                // Execute the post-test script
                // 
                System.Diagnostics.Trace.WriteLineIf((testActions.PosttestAction != null), "Executing post-test script...");
                ExecutionResult[] posttestResults = TestService.Execute(this.PrivilegedContext, this.PrivilegedContext, testActions.PosttestAction);
    
            }
    

分散トランザクション コーディネータ サービスを開始するには

このトピックの一部の手順では、System.Transactions アセンブリにある型を使用します。これらの手順に従う前に、単体テストを実行するコンピュータ上で分散トランザクション コーディネータ サービスを実行していることを確認してください。サービスが実行されていないと、テストが失敗し、"テスト メソッド ProjectName.TestName.MethodName は例外をスローしました: System.Data.SqlClient.SqlException: サーバー 'ComputerName' 上の MSDTC は利用できません" というエラー メッセージが表示されます。

分散トランザクション コーディネータ サービスを開始するには

  1. コントロール パネルを開きます。

  2. コントロール パネルの [管理ツール] を開きます。

  3. [管理ツール] で、[サービス] を開きます。

  4. [サービス] ペインで、[分散トランザクション コーディネータ] サービスを右クリックし、[開始] をクリックします。

    サービスの状態が [開始] に更新されます。これで、System.Transactions を使用する単体テストを実行できるようになります。