title: Unit testing with Mocks when SUT is leveraging Task Parallel Libaray
body: <p>I am trying to unit test / verify that a method is being called on a dependency, by the system under test (SUT). </p>
  
  <ul>
  <li>The depenedency is IFoo.</li>
  <li>The dependent class is IBar.</li>
  <li>IBar is implemented as Bar.</li>
  <li>Bar will call Start() on IFoo in a new (System.Threading.Tasks.)Task, when Start() is called on Bar instance.</li>
  </ul>
  
  <p>Unit Test (Moq):</p>
  
  <pre><code>    [Test]
      public void StartBar_ShouldCallStartOnAllFoo_WhenFoosExist()
      {
          //ARRANGE
  
          //Create a foo, and setup expectation
          var mockFoo0 = new Mock&lt;IFoo&gt;();
          mockFoo0.Setup(foo =&gt; foo.Start());
  
          var mockFoo1 = new Mock&lt;IFoo&gt;();
          mockFoo1.Setup(foo =&gt; foo.Start());
  
  
          //Add mockobjects to a collection
          var foos = new List&lt;IFoo&gt;
                         {
                             mockFoo0.Object,
                             mockFoo1.Object
                         };
  
          IBar sutBar = new Bar(foos);
  
          //ACT
          sutBar.Start(); //Should call mockFoo.Start()
  
          //ASSERT
          mockFoo0.VerifyAll();
          mockFoo1.VerifyAll();
      }
  </code></pre>
  
  <p>Implementation of IBar as Bar:</p>
  
  <pre><code>    class Bar : IBar
      {
          private IEnumerable&lt;IFoo&gt; Foos { get; set; }
  
          public Bar(IEnumerable&lt;IFoo&gt; foos)
          {
              Foos = foos;
          }
  
          public void Start()
          {
              foreach(var foo in Foos)
              {
                  Task.Factory.StartNew(
                      () =&gt;
                          {
                              foo.Start();
                          });
              }
          }
      }
  </code></pre>
  
  <p>Moq Exception:</p>
  
  <pre><code>*Moq.MockVerificationException : The following setups were not matched:
  IFoo foo =&gt; foo.Start() (StartBar_ShouldCallStartOnAllFoo_WhenFoosExist() in
  FooBarTests.cs: line 19)*
  </code></pre>