Wednesday, August 08, 2007 3:54 AM
by
elandes
Unit Testing Multithreaded methods.
[tags: ASP.NET, Test Driven Development, TDD, C#, VB.NET, Unit Testing]
On my latest project, our team encountered an issue where we had to use Threading for our business objects. So we enabled threading on our object. But our Unit Tests encountered problems when running with threading enabled. I had some issues with getting my unit tests to pass. After searching the web I couldn't find instructions on exactly how to do this, so thought I'd pass on my solution.
[TestMethod]
public void TestThreadedBusinessObject()
{
Object myObject = new Object();
myObject.MethodWithThreading();
WaitOnThreads(myObject);
Assert.IsTrue(myObject.GetAll().Count == 6);
}
private static void WaitOnThreads(Object PassedObject)
{
foreach (System.Threading.Thread objThread in PassedObject.workerThreads)
{
objThread.Join();
}
}
From the above code, you just need to make sure that the Passed object is setting has a workerThreads code in it, using similar code to this:
public IList<Thread> workerThreads;
That's how I'm currently doing this (my threading uses a thread queue with a varialbe number of threads started by the process. Hopefully this will help anyone having issues with unit testing threaded methods. HTH
Eric