I am trying to setup a unit test (NUnit) for some database functions such that I can start a transaction in my unit test and rollback the transaction at the end, thus keeping the database in the same state and the end of the test that it was at the beginning of the test.
The problem is that my production code already creates a transaction and so I am unsure how to set up this test. My production code looks something like this:
try
{
adapter.StartTransaction(System.Data.IsolationLevel.Serializable, "SaveTransaction");
SaveMedia(adapter, userId);
adapter.Commit();
m_mediaId = m_mediaEntity.MediaId;
}
catch (Exception e)
{
adapter.Rollback();
throw;
}
In my unit test code, I'm creating a the adapter and also starting a transaction. The code above dies on the StartTransaction call b/c there is already a transaction started. I can check first to see if a transaction is in progress and only create the transaction if not already started. But since the commit call executes, the rollback() call in my test code will not actually remove the entity just saved. I suppose I could also modify the code not to commit if the transaction was not created here, but that all seems a bit hokey.
So I'm looking for a better way to have my unit test set up a transaction such that it can be rolled back at the end to remove any inserted data - but this mechanism needs to work when the production code also creates a transaction.
Any ideas? Do I need to use savepoints in the transactions? Are there better ways to accomplish this?
Thanks,
Beth