title: Unit testing a mutex lock
body: <p>Our business has recently moved to a TDD style and I'm new at writing unit tests. The C# (.net 3.5) piece I'm writing now should be able to verify a separate process is running, as I understand it the best way using the Mutex class.</p>
  
  <p>So I have a method in my SrsUpdaterController class like so...</p>
  
  <pre><code>public bool IsUpdaterRunning()
  {
      Mutex srsUpdaterMutex = new Mutex(false, SRS_UPDATERGUID);
      if (srsUpdaterMutex.WaitOne(0)) //If SRS Updater is running
      {
          srsUpdaterMutex.ReleaseMutex();
          srsUpdaterMutex.Close();
          return false;
      }
      else                            
      {
          return true;
      }
  }
  </code></pre>
  
  <p>and I have a test </p>
  
  <pre><code>[TestMethod()]
  public void IsUpdaterRunningTrueTest()
  {
      SrsUpdaterController target = new SrsUpdaterController();
      string mutexGuid = SrsUpdaterController.SRS_UPDATERGUID;            
      bool expected = true;
      bool actual;
  
      Mutex srsUpdaterMutex = new Mutex(false, mutexGuid);            
      srsUpdaterMutex.WaitOne(3000);
      actual = target.IsUpdaterRunning();           
      srsUpdaterMutex.ReleaseMutex();
      srsUpdaterMutex.Close();
      Assert.AreEqual(expected, actual);            
  }
  </code></pre>
  
  <p>It doesn't work because the unit test and the IsUpdaterRunning method are called by the same thread, and so <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms682411%28v=vs.85%29.aspx" rel="nofollow">Windows is "smart" enough</a> to not make the process block its self. The problem is I WANT the process to block its self so that it simulates the mutex being claimed. Is there any way to do this? Or am I approaching unit testing/process synchronization/mutex management all wrong?</p>
  
  <p>(note, I did also try locking the Mutex on a separate thread launched from the test, but it still allowed me to claim the mutex in both places. Which is ok because I'd rather avoid threads when possible)</p>
  
  <p>Thanks in advance!</p>