Over the past few months I have really started to believe in the use of Mocks. When I first started using mocks, I started with NMock (mostly because that is what we had at work). Shortly after that I started playing around with Rhino Mocks at home.
Since I have been playing around with both frameworks, I thought I would create a series of post that compare and contrast the two. This initial post is going to be showing the differences in how to create and use stub objects.
Stubs are as defined my Fowler as :
Stubs provide canned answers to calls made during the test, usually not responding at all to anything outside what’s programmed in for the test. Stubs may also record information about calls, such as an email gateway stub that remembers the messages it ’sent’, or maybe only how many messages it ’sent’.
Creating stubs with Rhino Mocks:
Notice here that the creation of a mock involves only 2 lines of code. Also notice how you don't have to use 'magic strings' to define a property, you simply populate the method with your required value.
Creating stubs with NMock
Notice here that the creation of the same mock requires 3 lines, 1 more than Rhino Mocks. This to me is not that big of a deal. What does stand out to me is how NMock has the developer set a mock property value. Unlike Rhino Mocks where you simple set the property like you would in code, you have to traverses their framework to get the same result. The biggest difference however is the use of 'magic strings' when defining what property to use with the stub.
Analysis
After looking at the 2 different ways to create mocks did you notice how they differed? Rhino Mocks was built with Refactoring and TDD in mind. You will notice that Rhino Mocks creation is shorter, simpler and less error prone. The reason Rhino Mocks is less error prone is because of the lack of 'magic strings'. When a framework like these require the developer to hardcode property names or method names these CANNOT be found during refactoring. The only way to know something changed is by running the test. I would rather have my compiler tell me something was wrong.
Personally, I also like how Rhino Mocks is less code, Having to remember how to populate a stub is the last thing I want to have to do. NMock is simply too verbose in this situation.
Winner of Round 1:
Rhino Mocks
Next Time:
Next time I will show how the two different frameworks handle expectations on method calls.