I am working with visual studio test tools and Rhino mocks.
I am currently writing a unit test on a method that uses Parallel.ForEach to process data. This is the method I want to test:
var exceptions = new ConcurrentQueue<Exception>();
Parallel.ForEach(messages, emailMessage =>
{
try
{
this.Insert(emailMessage)
}
catch (Exception exception)
{
exceptions.Enqueue(exception);
}
});
if (exceptions.Count > 0)
{
throw new AggregateException(exceptions);
}
And this is my test:
[ExpectedException(typeof(AggregateException))]
public void MyTest()
{
this.target = new MyClassToTest();
// stub the throwing of an exception
this.target.Stub(
s => s.Insert(null)).IgnoreArguments().Throw(new ArgumentNullException());
// perform the test
this.target.Send();
}
In my test, I stub the insert method and force it to throw and exception. The expectation on my test is that an AggregateException is thrown. If I run the test within Visual Studio it runs fine but on a continuous integration server, the test intemetently times out. I expect this is an issue around the nature of Parallel.ForEach where the iterations of the loop are done in parallel.
Can anyone see where I am going wrong above or how I can alter my test to prevent it from timing out?