Mocks and Making Tests Easier to Read

[article]
Summary:

There has been a lot of recent discussion on Twitter about the use of mocking frameworks and writing readable tests. Here is a roundup of some of the recent blogs on the subject.


Making Tests More Readable

There has been a lot of recent discussion on Twitter about the use of mocking frameworks and writing readable tests. Here is a roundup of some of the recent blogs on the subject.

 

Making Tests More Readable

 

Brian Marick blogged on "Mocks, the removal of test detail, and dynamically-typed languages," in which he discussed techniques he uses in Ruby and Objective-J to make tests more readable. He provides an example where using mocks to verify interaction removes unnecessary detail from the tests, which would otherwise be present without using mocks. (For more information about the techniques he shows for setting up examples in the non-mock example, see the Generated Value pattern at xUnitPatterns.org.)

 

J.B. Rainsberger elaborated on techniques to make tests more readable in his post "What your tests don't need to know will hurt you." He offers this guiding principle for writing tests: "A test should make it clear how its expected output relates to its input," and provides some rules to clean up the tests.

 

Mocking Frameworks

 

Robert "Uncle Bob" Martin has had much to say about mocking frameworks on Twitter, in which he argues that while there are some times when mocking frameworks are valuable, but they can encourage developers to live with bad dependencies in their designs. One of his preferred cures is to write tests that verify the outcome rather than the interaction. (Interaction vs. State-Based Testing is one of the oldest discussions in the TDD community, see this article by Martin Fowler.)

 



No matter what opinion people have about mocking frameworks, everyone seems to agree: bad dependencies in production code are a smell should be broken. To quote J.B., "When you find it difficult to write a concise, focused, isolated test, the production code has unhealthy dependencies to loosen, invert, or break."

 

How do you keep your tests readable?

 

 

About the author

AgileConnection is a TechWell community.

Through conferences, training, consulting, and online resources, TechWell helps you develop and deliver great software every day.