views:

111

answers:

2

When writing a test for persistently stored data, I come up with a test along the lines of:

[TestMethod]
public void DoCreateDeleteTest() {
    PersistentDataStore pds = new PersistentDataStore();
    bool createSuccess = pds.Save("id", "payload");
    Assert.AreEqual(true, createSuccess);
    bool deleteSuccess = pds.Delete("id");
    Assert.AreEqual(true, deleteSuccess);
}

As long as everything works, this seems fine. The function has no prior dependencies and it cleans up after itself. The problem is: when the .Save() method performs the save but returns false/failure. The assertion fires and the delete is not called so it doesn't clean up after itself.

After this, there is persisted data in the database with name "id" and all future saves fail.

The only way I can think to get around it is to do a precautionary delete before the save, but that seems like way to large a hack.

A: 

Wrap both within the one transaction? Do a delete in a catch?

dove
If I was doing this kind of test (which is really an integration test), I used to used TransactionScope like this: http://bbits.co.uk/blog/archive/2006/07/31/12741.aspx. You can put the functionality in a base Transactional unit test class.
RichardOD
+3  A: 

Put the delete in a method marked with the TestCleanup attribute (I assume you are using MSTest).

By the way your test is also testing two different things: whether the save works and it also tests the delete. Tests should only test one thing at a time.

Gerrie Schenck
Thanks, I think I was hung up on making the "Test" clean up after itself rather than making sure the "TestFixture" was clean. The observation that I was testing two different things was a real d'oh moment.
Adrian