title: Unstable unit test result - mock message queue behavior and parallel loop
body: <p>I am building a class to use parallel loop to access messages from message queue, in order to explain my issue I created a simplified version of code:</p>
  
  <pre><code>public class Worker
  {
      private IMessageQueue mq;
      public Worker(IMessageQueue mq)
      {
          this.mq = mq;
      }
  
      public int Concurrency
      {
          get
          {
              return 5;
          }
      }
  
      public void DoWork()
      {
          int totalFoundMessage = 0;
  
          do
          {
              // reset for every loop
              totalFoundMessage = 0;
  
              Parallel.For&lt;int&gt;(
                  0,
                  this.Concurrency,
                  () =&gt; 0,
                  (i, loopState, localState) =&gt;
                  {
                      Message data = this.mq.GetFromMessageQueue("MessageQueueName");
  
                      if (data != null)
                      {
                          return localState + 1;
                      }
                      else
                      {
                          return localState + 0;
                      }
                  },
                  localState =&gt;
                  {
                      Interlocked.Add(ref totalFoundMessage, localState);
                  });
          }
          while (totalFoundMessage &gt;= this.Concurrency);
      }
  }
  </code></pre>
  
  <p>The idea is to set the worker class a concurrency value to control the parallel loop. If after each loop the number of message to retrieve from message queue equals to the concurrency number I assume there are potential more messages in the queue and continue to fetch from queue until the message number is smaller than the concurrency. The TPL code is also inspired by <a href="https://stackoverflow.com/questions/14364374/tpl-data-parallelism-issue">TPL Data Parallelism Issue</a> post.</p>
  
  <p>I have the interface to message queue and message object.</p>
  
  <pre><code>public interface IMessageQueue
  {
      Message GetFromMessageQueue(string queueName);
  }
  
  public class Message
  {
  }
  </code></pre>
  
  <p>Thus I created my unit test codes and I used Moq to mock the <code>IMessageQueue</code> interface</p>
  
  <pre><code>    [TestMethod()]
      public void DoWorkTest()
      {
          Mock&lt;IMessageQueue&gt; mqMock = new Mock&lt;IMessageQueue&gt;();
  
          Message data = new Message();
  
          Worker w = new Worker(mqMock.Object);
  
          int callCounter = 0;
          int messageNumber = 11;
          mqMock.Setup(x =&gt; x.GetFromMessageQueue("MessageQueueName")).Returns(() =&gt;
          {
              callCounter++;
              if (callCounter &lt; messageNumber)
              {
                  return data;
              }
              else
              {
                  // simulate MSMQ's behavior last call to empty queue returns null
                  return (Message)null;
              }
          }
          );
  
          w.DoWork();
  
          int expectedCallTimes = w.Concurrency * (messageNumber / w.Concurrency);
          if (messageNumber % w.Concurrency &gt; 0)
          {
              expectedCallTimes += w.Concurrency;
          }
  
          mqMock.Verify(x =&gt; x.GetFromMessageQueue("MessageQueueName"), Times.Exactly(expectedCallTimes));
      }
  </code></pre>
  
  <p>I used the idea from <a href="https://stackoverflow.com/questions/14368380/moq-to-set-up-a-function-return-based-on-called-times">Moq to set up a function return based on called times</a> to set up call times based response.</p>
  
  <p>During the unit testing I noticed the testing result is unstable, if you run it multiple times you will see in most cases the test passes, but occasionally the test fails for various reasons.</p>
  
  <p>I have no clue what caused the situation and look for some input from you. Thanks </p>