unit tests, TransactionScope and threads

unit tests, TransactionScope and threads

Old forum URL: forums.lhotka.net/forums/t/10342.aspx


richardp posted on Wednesday, May 04, 2011

Hi,

I am trying to unit test our CRUD code for our CSLA project.

I am using NUnit.

I was hoping to use TransactionScope to clean up the database after each test.

E.g. something like this..

[SetUp]

public void SU()

{

_transactionScope = new TransactionScope();

}

[TearDown]

public void TD()

{

_transactionScope.Dispose();

}

[Test]

public void TestUpdate()

{

// update or insert stuff, check it worked

}

I have come up against 2 issues.

1) If I use asynchronous updates e.g. Object.BeginSave() the unit tests pass but the test data is left in the database.

I think this is because the update is done on a different thread, and TransactionScope does not work across threads.

I read in MSDN you need to use DependentTransaction for that. 

My workaround is to use only synchronous updates e.g. Object.Save().  - then the transaction scope seems to rollback the changes on Dispose().

2) Some fields in our objects use asynchronous rules, which go to the database and check if the field is unique.

In the unit test, if we are inside a TransactionScope, and something in the dbase is modified, and one of these rules is run, it results in deadlock.

I have stepped thru it again and again but can't seem to get a handle on it.

I think the async rule thread has to wait for the current transaction to complete before it is allowed to access the dbase??

The async rules are read-only and do not modify any data.

Anyone got any ideas on how to work around this?

Cheers.

Copyright (c) Marimer LLC