views:

328

answers:

1

In my research about rolling back transactions in EF4, it seems everybody refers to this blog post or offers a similar explanation. In my scenario, I'm wanting to do this in a unit testing scenario where I want to rollback practically everything I do within my unit testing context to keep from updating the data in the database (yeah, we'll increment counters but that's okay). In order to do this, is it best to follow the following plan? Am I missing some concept or anything else major with this (aside from my SetupMyTest and PerformMyTest functions won't really exist that way)?

[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
  }
}
+1  A: 

We use TransactionScope for this.

    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();
    }

This will rollback any changes made in any of the tests.

Shiraz Bhaiji
Do you have issues with hanging transactions when writing/debugging the tests? I'd prefer to be doing this against a shared database but I don't want to do this in a way where we're constantly dealing with hanging transactions.
Jaxidian
You get hanging transactions if you do not do a dispose. Without the dispose the transaction will hang until it timesout.
Shiraz Bhaiji
Any chance you can update your code sample to show what a basic test looks like? Is `SaveChanges(SaveOptions.AcceptAllChangesAfterSave)` the right way to go about this or not?
Jaxidian