Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NUnit Rollback After Test

I am pretty new to NUnit (and automated testing in general). I have recently done some Ruby On Rails work and noticed that in my test suite, when I create objects (such as a new user) and commit them during course of the suite, they are never committed to the database so that I can run the test over and over and not worry about that user already existing.

I am now trying to accomplish the same thing in NUnit, but I am not quite sure how to go about doing it. Do I create a transaction in the Setup and Teardown blocks? Thanks.

like image 638
skaz Avatar asked Apr 28 '11 12:04

skaz


2 Answers

Maybe you can use this. It is ugly, but perhaps it can work for you:

namespace SqlServerHandling
{
[TestFixture]
public sealed class TestTransactionRollBacks
{

    private string _connectionString = "Data Source = XXXDB; ; Initial Catalog = XXX; User Id = BLABLA; Password = BLABLA";
    private SqlConnection _connection;
    private SqlTransaction _transaction; 


    [SetUp]
    public void SetUp()
    {
        _connection = new SqlConnection(_connectionString);
        _transaction = _connection.BeginTransaction();
    }

    [TearDown]
    public void TearDown()
    {
       _transaction.Rollback();
    }


    [Test]
    public void Test()
    {
        Foo foo = new Foo(_connection);

        object foo.Bar();



    }


}

internal class Foo
{
    private readonly SqlConnection _connection;
    object someObject = new object();
    public Foo(SqlConnection connection)
    {
        _connection = connection;
    }

    public object Bar()
    {
        //Do your Stuff
        return someObject;
    }
} 
like image 164
Morten Avatar answered Sep 29 '22 03:09

Morten


I agree with Morten's answer, but you might want to look at this very old MSDN Magazine article on the subject: Know Thy Code: Simplify Data Layer Unit Testing using Enterprise Services

like image 40
Mark Seemann Avatar answered Sep 29 '22 02:09

Mark Seemann