Some days ago I came in this issue regarding thread non-safety when using MoQ. So I simple create my own fork on GitHub and solved the issue, that was really easy to do, and as a result I obtained a Mock stable even when mocked methods are called from multiple threads. I created a bounch of test to prove that worked, here below one as a sample:
So with this I made the Mock thread safe at the infrastructure level, that mean no more strange NullreferenceException and others. But what if we want our mock not thread safe? I mean there could be situation in which we want to ensure the system under test calls a certain method from a single thread, in other word we want the mock to explicitly require single thread access to certain methods. This could happen for example when we are mocking some UI components, but there is such situations every time the object we are mocking is intrinsically non thread safe and the SUT is multithreaded. So I extended the MoQ fluent language from the internal and I obtain something like… the example below:
So in the setup phase we declare a method ( or a setter, or a getter, as usual ) to be SingleThread(). This yield a mock throwing when the method is called from a different thread from the one which did the setup.
If you are happy with this modifications ( you would for sure find helpful the thread safety by its own ) feel free to check out my code fork on GitHub, in any case I’m trying to have that modification pulled from the main stream.