chapter seven

7 Refactoring toward valuable unit tests

 

This chapter covers:

  • Recognizing the four types of code
  • Understanding the Humble Object pattern
  • Writing valuable tests

In chapter 1, I defined the properties of a good unit test suite:

  • It is integrated into the development cycle.
  • It targets only the most important parts of your code base.
  • It provides maximum value with minimum maintenance costs. To achieve this last attribute, you need to be able to:

    • Recognize a valuable test (and, by extension, a test of low value).
    • Write a valuable test.

Chapter 4 covered the topic of recognizing a valuable test using the four attributes: protection against regressions, resistance to refactoring, fast feedback, and maintainability. And chapter 5 expanded on the most important one of the four: resistance to refactoring.

As I mentioned earlier, it’s not enough to recognize valuable tests, you should also be able to write such tests. The latter skill requires the former, but it also requires that you know code design techniques. Unit tests and the underlying code are highly intertwined, and it’s impossible to create valuable tests without putting effort into the code base they cover.

7.1  Identifying the code to refactor

7.1.1  The four types of code

7.1.2  Using the Humble Object pattern to split overcomplicated code

7.2  Refactoring toward valuable unit tests

7.2.1  Introducing a customer management system

7.2.2  Take 1: Making implicit dependencies explicit

7.2.3  Take 2: Introducing an application services layer

7.2.4  Take 3: Removing complexity from the application service

7.2.5  Take 3: Introducing a new Company class

7.3  Analysis of optimal unit test coverage

7.3.1  Testing the domain layer and utility code

7.3.2  Testing the code from the other three quadrants

7.3.3  Should you test preconditions?

7.4  Handling conditional logic in controllers

7.4.1  Using the CanExecute/Execute pattern

7.4.3  Conclusion