title: Mocking a method that uses an asynchronous callback with moq
body: <p>I'm unit testing some asynchronous code. I have tried to abstract it to make the issue more clear. My issue is that I want to set up the mocked <code>Bar</code> to execute <code>Foo</code>'s private callback method after <code>BeginWork</code> returns. The callback is supposed to call <code>Set()</code> on the <code>ManualResetEvent</code> allowing the calling thread to continue to run. When I run the test my thread blocks indefinitely at the call to <code>WaitOne()</code>.</p>
  
  <p>Code under test:</p>
  
  <pre><code>using System.Threading;
  using NUnit.Framework;
  using Moq;
  using System.Reflection;
  
  public interface IBar
  {
      int BeginWork(AsyncCallback callback);
  }
  
  public class Bar : IBar
  {
      public int BeginWork(AsyncCallback callback)
      {
          // do stuff
      }   // execute callback
  }
  
  public class Foo
  {
      public static ManualResetEvent workDone = new ManualResetEvent(false);
      private IBar bar;
  
      public Foo(IBar bar)
      {
          this.bar = bar;
      }
  
      public bool DoWork()
      {
          bar.BeginWork(new AsyncCallback(DoWorkCallback));
          workDone.WaitOne(); // thread blocks here
          return true;
      }
  
      private void DoWorkCallback(int valueFromBeginWork)
      {
          workDone.Set();
      }
  }
  </code></pre>
  
  <p>Test Code:</p>
  
  <pre><code>[Test]
  public void Test()
  {
      Mock&lt;IBar&gt; mockBar = new Mock&lt;IBar&gt;(MockBehavior.Strict);
  
      // get private callback
      MethodInfo callback = typeof(Foo).GetMethod("DoWorkCallback", 
                    BindingFlags.Instance | BindingFlags.NonPublic);
  
      mockBar.Setup(() =&gt; BeginWork(It.IsAny&lt;AsyncCallback&gt;())) 
                          .Returns(0).Callback(() =&gt; callback.Invoke(0));
  
      Foo = new Foo(mockBar.Object);
      Assert.That(Foo.DoWork());
  }
  </code></pre>