2

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?

jessehouwing
  • 106,458
  • 22
  • 256
  • 341
amateur
  • 43,371
  • 65
  • 192
  • 320
  • 1
    Side note: stubbing half of the methods of a class that your are testing looks very suspicious (unlikely to cause error, so posting as comment). – Alexei Levenkov Aug 17 '12 at 15:43
  • 1
    There are some text missing around " If I run the test within Visual Studio but on y continuous..." (look like you wanted to say that it succeeds in one environment and fails in another, but I'm afraid to edit it myself as it could change meaning of the question). – Alexei Levenkov Aug 17 '12 at 15:45
  • 1
    The try catch logic you've implemented is about the same what Parallel.ForEach already does under the covers. – Steven Aug 17 '12 at 17:04
  • Could be a locking issue? Have you tried using the lock keyword before your Insert? – Alex Oct 15 '13 at 12:51
  • What does Insert do? Is it actually parallizable? Does the test work with a "normal" foreach loop? It's possible that Parallel.ForEach will actually degrade performance under certain circumstances. – EJoshuaS - Stand with Ukraine Dec 29 '16 at 17:39

0 Answers0