Click here to Skip to main content
15,890,043 members
Articles / All Topics

Moq4 Thread Safety and More

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
22 Mar 2012CPOL1 min read 9.9K   3  
My solution to Moq4 thread safety issue

Some days ago, I came to this issue regarding thread non-safety when using MoQ. So I simply created 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 bunch of tests to prove that worked. Given below is a sample:

clip_image001

So with this, I made the Mock thread safe at the infrastructure level, that means 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 words, 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 are 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:

moqts

So in the setup phase, we declare a method (or a setter, or a getter, as usual) to be SingleThread(). This yields a mock throwing when the method is called from a different thread from the one which did the setup.

If you are happy with these modifications (you would for sure find helpful the thread safety on 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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Italy Italy
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --