Earlier today I had a pretty good discussion regarding multithreaded unit tests and the best way to accomplish them. For example we want a way to find deadlocks in our applications and so on. Some may say that that's not really unit testing, but integration testing. Fair enough, and that's a debate for another time.
If you're a fan of MbUnit as I am, you'll probably notice the goodness of the
ThreadedRepeatAttribute. This custom attribute when applied to a Test method can run the given method concurrently on the given amount of threads.
[
Test]
[
ThreadedRepeatAttribute(5)]
public void XmlConverter_Convert_Multithreaded_ReturnsSuccess()
{
// Execute code and assert
}
Seems easy, yes? But it doesn't give you much control to parameterize it the way it's written.
Roy Osherove weighed in on the matter and has introduced his own multi-threading testing solution. Part of the code provided will be going into his upcoming book. This solution is built using NUnit and a basic test could look like this:
[Test]
public void XmlConverter_Convert_Multithreaded_ReturnsSuccess()
{
Counter counter =
new Counter();
ThreadTester tester =
new ThreadTester();
for (
int i = 0; i < 5; i++)
{
tester.AddThreadAction(
delegate
{
// Execute code and assert
});
}
tester.RunBehavior=
ThreadRunBehavior.RunUntilAllThreadsFinish;
tester.StartAllThreads(500);
}
In a rather old article
Oren, aka Ayende, tackles the problem in his copious spare time. He was given a challenge of finding deadlocks with the TDD approach and mutexes. Sample code is always available.
I like the cleaner code when it comes to this and want the infrastructure to handle all of this for me. So, a lot of this setup for some of these tests are no-gos. I'm still working on a perfect solution though and to see if we could make things a bit more dynamic. Thoughts?