65.9K
CodeProject is changing. Read more.
Home

Moq4 Thread Safety and More

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Mar 22, 2012

CPOL

1 min read

viewsIcon

10246

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.