6

EF4でのトランザクションのロールバックに関する私の調査では、誰もがこのブログ投稿を参照しているか、同様の説明を提供しているようです。私のシナリオでは、単体テストのシナリオでこれを実行したいと考えています。単体テストのコンテキスト内で行うすべてのことをロールバックして、データベース内のデータが更新されないようにします(ええ、カウンターをインクリメントしますが、それで問題ありません)。 )。これを行うには、次の計画に従うのが最善ですか?私はこれに関していくつかの概念または他の主要なものを見逃していますか(私の関数SetupMyTestPerformMyTest関数は実際にはそのように存在しないことを除いて)?

[TestMethod]
public void Foo
{
  using (var ts = new TransactionScope())
  {
    // Arrange
    SetupMyTest(context);

    // Act
    PerformMyTest(context);
    var numberOfChanges = context.SaveChanges(SaveOptions.AcceptAllChangesAfterSave);
    // if there's an issue, chances are that an exception has been thrown by now.

    // Assert
    Assert.IsTrue(numberOfChanges > 0, "Failed to _____");

    // transaction will rollback because we do not ever call Complete on it
  }
}
4

1 に答える 1

10

これにはTransactionScopeを使用します。

    private TransactionScope transScope;

    #region Additional test attributes
    //
    // Use TestInitialize to run code before running each test 
    [TestInitialize()]
    public void MyTestInitialize()
    {
        transScope = new TransactionScope();
    }

    // Use TestCleanup to run code after each test has run
    [TestCleanup()]
    public void MyTestCleanup()
    {
        transScope.Dispose();
    }

これにより、いずれかのテストで行われた変更がロールバックされます。

于 2010-04-21T20:55:05.490 に答える