Preferred way to mock/stub a system resource like System.Threading.Mutex

572 views Asked by At

I have a c# class that uses a Mutex to control access to a global shared resource. The Mutex is not assigned unless the shared resource is created. I'm using a partial mock of the class to isolate testing of certain methods that grab the mutex, do some work, and release it (without ever actually creating the shared resource or the mutex instance).

I'm curious to know if there is a preferred way of mocking the mutex. I could abstract the real calls to WaitOne and ReleaseMutex into methods on the class and mock those. I could explicitly assign a new mutex instance to the class' mutex member variable in the test (assuming I compromise and make the setter accessible to the unit test). I could wrap the mutex in another class that implements a parallel interface to the mutex methods and inject that into my class under test.

Are there better ways of mocking system resources like System.Threading.Mutex? Thus far I've opted to abstract the real calls into methods on the class and mock them.

1

There are 1 answers

1
Andy Nichols On

Look into the Microsoft Fakes Framework. It has something called shims which work a little differently to stubs or mocks as they divert the calls to a delegate.

The framework will create a class for you called ShimMutex. In your test class you would write delegates to redirect the Mutex methods you use and then write code in your test along the lines of:

using (ShimsContext.Create())
{
    System.Fakes.ShimMutex.AllInstances.WaitOne = () => { some code };
    System.Fakes.ShimMutex.AllInstances.ReleaseMutex = () => { some code };
    //The rest of your test
}

NOTE: Shims is something I have looked into but not used yet - so my answer is based on the documentation rather than experience. Their documentation is pretty thorough though.