Martin Fowler has a great post entitled Mocks Aren't Stubs. Go ahead and read/skim through that if you haven't. Of the two categories of TDDers he defines, I am definitely a mockist. That is, I almost always "use a mock for any object with interesting behavior". I do use Mocks and Stubs, but those stubs are generally just Mocks set up to be stubs (as it's easier than stubbing a class myself.) That said, I do have a few ground rules for when I write tests with Rhino Mocks that sort fall into the whole one assertion per test topic and the mocks vs. stubs thing. Here they are:
- Name TestMethods MethodOrPropertyName_Scenario_ExpectedResult. I stole this from someone, but I can't remember who. If you know what post that was, let me know so I can link it. An example is: CalculateCost_WhenProductIsNull_ThrowsException. I just think this makes your intent very clear and readable.
- Never use _mocks.Ordered() unless you are actually testing the order in which something is called... and if you are, test only that!
- Unless you're testing that something gets called once and only once (expensive method? caching?), use Repeat.Any(). Who cares if it gets called again?
- Prefer DynamicMock over CreateMock (standard mocks). Here's an example. You're testing that your controller sets FirstName on a view. You write that test and implement the feature. Two days later you need to add EmailAddress to that view, so you write your test to ensure that it is added. You implement it and run your tests... now, if you used a standard mock, your original FirstName test would fail! With a DynamicMock however, you have no tests to "fix" (tests should rarely need to be fixed because you added something to the class that has no bearing on the originally tested scenario)
- Don't use VerifyAll. What!?!? That's right, half the time I use Verify(someMock) and the other half I don't even Verify anything (as I can verify the result of a method called). Your tests should be complete enough that it shouldn't matter if ObjectA called ObjectB as long as ObjectA gives you the correct result.
Remember, Verification, Ordering, setting a fixed # of repeats, requiring every method/property to be "expected", etc, are all Assertions. I'm not steadfast on the whole one assertion per test thing, as sometimes a few assertions make sense. As long as you at least think about what your test would be named if you put every assertion in the method name of the test, I think that a lot of these rules would make more sense.... Would you rather diagnose a break in SomeMethod_WhenSomeObjectIsGreen_CallsFooTwiceThenCallsBarWithResultOfFoo
OnceThenSetsColorAndShapeAndResultOfFoo() or SomeMethod_WhenSomeObjectIsGreen_SetsColor()? :)