Chapter 14. Testing and Readability

image with no caption

In this chapter, we’re going to show you simple techniques to write neat and effective tests.

Testing means different things to different people. In this chapter, we use “test” to mean any code whose sole purpose is to check the behavior of another (“real”) piece of code. We’re going to focus on the readability aspect of tests and not get into whether you should write test code before writing real code (“test-driven development”) or other philosophical aspects of test development.

Make Tests Easy to Read and Maintain

It’s just as important for test code to be readable as it is for nontest code. Other coders will often look at the test code as unofficial documentation of how the real code works and should be used. So if the tests are easy to read, users will better understand how the real code behaves.

Key Idea

Test code should be readable so that other coders are comfortable changing or adding tests.

When test code is big and scary, here’s what happens:

  • Coders are afraid to modify the real code. Oh, we don’t want to mess with that code—updating all the tests would be a nightmare!

  • Coders don’t add new tests when they add new code. Over time, less and less of your module is tested, and you are no longer confident that it all works.

Instead, you want to encourage users of your code (especially you!) to be comfortable with the test ...

Get The Art of Readable Code now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.