Search code examples
.netmockingmoles

How does Moles differ from other isolation frameworks, such as Moq, RhinoMocks etc


Pretty much as it says above. I'm wondering how it's different. Being a product from Microsoft, does it do similar things to more common frameworks, but with new names, or slightly differently; just apparently to make like difficult... e.g. MsTest.

How fully-fledged is it? Production-ready? It is meant to do more than Moq etc. (like MsTest is not simply a unit-testing framework). Does it cover the same mocking-ground. Does it do some things worse? Better?

I'm thinking of taking a look at it, but with so many frameworks around these days, I'm wondering what the benefit is.


Solution

  • Mocking frameworks and isolation frameworks are really two similar but different things. Mocking and stubbing frameworks typically are referenced libraries that allow you to create a stub implementation of an interface (to fake out behavior) or mocking (to verify that behavior was called). Isolation frameworks generally work at the CLR and allow you to instrument into just about any area of code (your own others) you want. Moles (which is part of Pex) is an isolation framework still in the research division of Microsoft (http://research.microsoft.com/en-us/projects/pex/). With Moles, you can pretty much isolate any section of your code (or any code in the CLR) and control how it behaves. For example with Moles, you could intercept the DateTime.Now() and return a set date and time to use for testing date-dependent calculation. It is also useful when you have a black-box third-party library that you cannot control.

    The downside to Moles is that it is a little bit more complicated than using a mocking framework like Moq or RhinoMocks. This added functionality makes Moles' learning curve a little steeper. Also, while you can stub an interface with Moles fairly easily and use it in a CI build, when you actually instrument into Moles you "mole" and generate a new assembly with the proper hooks into new .dll. On larger projects, this might increase the build-time slightly. Finally, I've had some issues getting Moles to work in TFS build and test deployments (but that could just be me).

    I wouldn't really make this an "either-or" situation. I would primarily use Moq for most of my needs and try to write my code to be testable using a conventional framework. If, however, you get stuck in a situation where you cannot easily isolate your code for various unit tests, I'd use Moles for those situations.

    Finally, go read Martin Fowler's article "Mocks Aren't Stubs" (http://martinfowler.com/articles/mocksArentStubs.html). In my opinion it is the best description of what you really want to try to do with mocking and stubbing.