The Object Mother is a popular testing pattern, mostly used as a factory during test setup. It allows the creation of nice DSLs, making it easy to build complex objects during test set up (leaving DRY tests, always a good thing!).
Unfortunately, I’ve recently started to see it as more and more of a test “smell”. Especially when unit testing.
I find people use it to brush an oversized test setup under the carpet. Rather than listening to their tests, and fixing the code, they use a builder to hide the size and complexity of the setup required.
I’ve noticed it particularly in combination with AutoMapper (an excellent tool, and certainly not to blame for it’s misuse). And the use of the static Mapper methods which, sadly, most of the examples use.
Because the mapper requires a realistic object, else it will throw, you end up needing to set a lot of properties on parameter objects passed in.
In this case, the solution is obvious. Break the coupling between your code & the mapper. Wrap the mapping calls in an interface (whether you use IMappingEngine, or roll your own), and mock them.
This gets you back to a true unit test, rather than combining the complexity of the mapping code with the class you’re trying to test.
So should we abandon the Object Mother?
Certainly not. It’s an incredibly useful tool, particularly when writing acceptance tests, where the complexity is a necessary evil.
But make sure you’re using it for the right reason, not taking the easy way out.