Is data rollback possible with TransactionScope?

The goal is simple - rollback data inserted by unit test. Here's how it goes. In the unit test, a method is called that creates a new connection and inserts some data. After that, unit test creates a new connection and tries to find what was inserted and claim it. I was hoping to wrap these two things with help TransactionScope, rather than invoking Completeand looking at the inserted data. This is not happening. Am I doing something wrong, or is there just not enough meaning?

using (new TransactionScope())
{
    // call a method that inserts data
    var target = new ....
    target.DoStuffAndEndupWithDataInDb();

    // Now assert what has been added.
    using (var conn = new SqlConnection(connectionString))
    using (var cmd = conn.CreateCommand())
    {
        // Just read the data from DB
        cmd.CommandText = "SELECT...";
        conn.Open();
        int count = 0;
        using (var rdr = cmd.ExecuteReader())
        {
            // Read records here
            ...
            count++;
        }

        // Expecting, say, 3 records here
        Assert.AreEqual(3, count);
    }
}

EDIT: I don’t think DTC was running and configured on my computer. So I started the service and tried to configure DTC, but I get this error. enter image description here

+5
source share
4

MSTest? MsTestExtensions unit test MSTestExtensionsTestFixture, TestTransaction, AOP, .

+1

, , .

NUnit [SetUp] [TearDown]. , , ( , ).

+1

? TransactionScope ... , , , .

, , MSDTC.

+1

, . DoStuffAndEndupWithDataInDb()? , .

3 rows ( SSMS).

public class Program
{
    private static void Main(string[] args)
    {
        using (var trx = new TransactionScope())
        {
            InitializeData();

            using (var connection = new SqlConnection("server=localhost;database=Test;integrated security=true"))
            using (var command = connection.CreateCommand())
            {
                command.CommandText = "select count(*) from MyTable";
                connection.Open();
                Console.WriteLine("{0} rows", command.ExecuteScalar());
            }
        }
        Console.ReadLine();
    }

    private static void InitializeData()
    {
        using (var connection = new SqlConnection("server=localhost;database=Test;integrated security=true"))
        using (var command = connection.CreateCommand())
        {
            command.CommandText = "insert into MyTable values (1),(2),(3)";
            connection.Open();
            command.ExecuteNonQuery();
        }
    }
}
0
source

All Articles