Wednesday, 27 March 2013

Moq As<> a code smell

The moq As method allows you to create a mock object that implements more than one interface:

(If IFirstInterface implements ISecondInterface then the As<> is not required.)

Its easy to see how this could help you write a test if the SUT cast the object of type IFirstInterface to ISecondInterface.

But what does this say about the code?

It's saying that you have a class that needs to implement more than one interface in order to performs it's job correctly. When you have a class that implements more than one interface, it suggests it has more than use, more than one reason to change. The need to use As<> is suggesting a Single Responsibility Principle violation.

While I wouldn't expect to see As<> used in tests for a Domain Model or Business Logic, it is possibly useful in "plumbing" layers, such as when adapting an external service. As always with code smells, use your own judgement.

No comments: