TransactionScope does not roll back in MSTest test

I have the following base object in my tests

[TestClass]
public abstract class TestClassBase
{
    private TransactionScope _transactionScope;

    [TestInitialize]
    public virtual void TestInitialize()
    {
        _transactionScope = new TransactionScope(TransactionScopeOption.RequiresNew, new TransactionOptions { Timeout = new TimeSpan(0, 10, 0) });
    }

    [TestCleanup]
    public virtual void TestCleanup()
    {
        _transactionScope.Dispose();
    }
}

I have a test that runs the following

[TestMethod]
public void SaveToDatebaseTest(
{
     Program program = new Program();         
     program.Name = "Unit Test Program, I should not exists, when Test is done";
     ProgramManager programManager = new ProgramManager()
     programManager.Save(program);
}

When I run the test, the records still exist in the database.

I want to avoid using TransactionScope in every test method

+3
source share
5 answers

You need to change your TestCleanup method, right now you are disposing of TransactionScope, I believe that it actually does implicit commit? (you might think that you would need to call Complete (), though?), since there are no errors, this is not a transaction rollback.

try it

[TestCleanup]
public virtual void TestCleanup()
{
    // using System.Transactions;
    Transaction.Current.Rollback();
    _transactionScope.Dispose();
}
+3
source

, , -, / , . ,

  • Entity Framework
  • Nunit (v3)

.

class A
{
     private TransactionScope _trans;

     [SetUp]
     public void setup()
     {
        _trans = new TransactionScope();
     }

     [TearDown]
     public void done()
     {
        if(_trans != null)
          _trans.Dispose();
     }

     [Test]
     public void doSomeDbWrite()
     {
         //your code to insert/update/delete data in db
     }
}

( ), TransactionScope, . , - EF, , , - . . , , EF , , unit test unit test.

class A
{
     private DbContext_DB;
     private DbContextTransaction _trans;

     [SetUp]
     public void setup()
     {
        DB = new DbContext();//create your db context
        _trans = DB.Database.BeginTransaction();
     }

     [TearDown]
     public void done()
     {
        _trans.Rollback();
        DB = null;
     }
}

, , : -)

+1

VS2005 VS2008 ( 2010 ), MSTestExtensions . MS SQLServer, Distributed Transaction Coordinator.

, , , .

0

, , , , , ? , ? , [TestInitialize] [TestCleanup], . (. fooobar.com/questions/127515/...).

0

, . , :

    private readonly TransactionScope _scope;

    public MyTests()
    {
        var options = new TransactionOptions()
        {
            IsolationLevel = IsolationLevel.Snapshot
        };

        _scope = new TransactionScope(TransactionScopeOption.Required, options,  TransactionScopeAsyncFlowOption.Enabled);
      }

      [TestCleanup]
      public void Cleanup()
      {
          _scope.Dispose();
      }
0

Source: https://habr.com/ru/post/1790575/


All Articles