Pages

Tuesday, February 23, 2010

Database Unit Testing in C#

Sometimes you need to write Unit Tests, where a test may alter the database.  But you don't want it to persist there after the test.  You also don't want to drop and re-create the database every time you run a test either, because you may have stuff in it for whatever reason.

#region Init and Cleanup

TransactionScope _trans;

[TestInitialize()]
public void Init()
{
     _trans = newTransactionScope();
}

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

This creates a transaction scope before each of your test methods and disposes of the transaction afterwards.  During the test, everything behaves as if you actually save in the database.  Afterwards, everything is as it was before!

No comments:

Post a Comment