I have just read a good post by Richard Dingwall called Law of Demeter is easy to spot when you need extra mock. He shows how you can spot violations of the Law of Demeter when you have to create extra mocks in order to stub a single method.
While I totally agree with his points about the Law of Demeter, it might not be so easy to spot violations thanks to a feature of Moq called auto-mocking hierarchies (a.k.a. recursive mocks). In this post I will show how this cool feature can simplify your tests.
System under test
Below is the code from Richard’s post that are under test:
The DoSomething method calls into the privates of IProfile (this is the violations of the law).
Test without recursive mocks
Below is the test without recursive mocks:
In this test we need to create an extra mock of the type IProfile to be able to mock IFoo. This makes the test much harder to read. Imagine the horror if another class was also part of the call chain.
Test with recursive mocks
Below is a simplified test that uses the recursive mocks feature of Moq:
As you can see, we have eliminated the need for the IProfile mock. This results in a much cleaner test.
In this post I have shown you a cool feature of Moq that can greatly simplify your mocking code. Of course you should still try to spot violations of the Law of Demeter, even though the extra mocks will no longer help you with this. Just remember that the law is really more of a guideline, but I guess Rule of thumb of Demeter doesn’t sound as catchy
If you want to read a great post (and discussion) about this law (eh guideline) check out The Law of Demeter Is Not A Dot Counting Exercise by Phil Haacked.
If you liked this post then please shout and kick me