title: Using Rhino Mocks to assert that a method was called after a given period of time
body: <p>Does anyone know if it's possible to use Rhino Mocks to check if a method was called within  a given period of time?</p>
  
  <p>Here's the code I want to write a unit test for:</p>
  
  <pre><code>while (true)
      if (TimeoutErrorStopwatch.IsRunning &amp;&amp; 
          TimeoutErrorStopwatch.ElapsedMilliseconds &gt; timeoutErrorTime)
      {
          someClass.HandleError();
      }
      else
          Thread.Sleep(10);
  </code></pre>
  
  <p>I want to write a unit test that ensures that the error is caught by checking whether the HandleError method was called. This loop is running on its own background thread, so I'm wondering if there's a way to assert that the method was called with a constraint to keep checking and assert that the method is called within a given time. Something to the effect of:</p>
  
  <pre><code>someClass.AssertWasCalled(s =&gt; s.HandleError()).Within(10);
  </code></pre>
  
  <p>My current work-around is I simply call <code>Thread.Sleep(10)</code> and then use <code>AssertWasCalled</code>, but I'm wondering if something like this is supported in Rhino Mocks.</p>
  
  <p>Thanks!</p>
  
  <p>------ EDIT ------</p>
  
  <p>In light of the comment, I wrote an extension method that checks to see if the method has been called until the given time limit has been reached, sleeping in between failed calls. I have actually already mocked the timers (in the real application, the timeout is set to 30 minutes whereas in my test I have set mock values of 100 milliseconds or less). I thought I would post my extension in case anyone stumbles upon this post.</p>
  
  <pre><code>public static void AssertWasCalledWithin&lt;T&gt;(this T stub, Action&lt;T&gt; action, long milliseconds)
      {
          var timer = Stopwatch.StartNew();
          var e = new Exception();
          while (timer.ElapsedMilliseconds &lt;= milliseconds)
              try
              {
                  stub.AssertWasCalled(action);
                  return;
              }
              catch (ExpectationViolationException exc)
              {
                  e = exc;
                  Thread.Sleep(1);
              }
  
          throw new ExpectationViolationException(
              string.Format(
                  "The following expectation was not met within the " +
                  "given time limit of {0} milliseconds: {1}",
                  milliseconds, e.Message));
      }
  </code></pre>