Readability is one of the key components to creating high quality unit and integration tests. Yet, we may hinder the readability of our tests by bogging them down with needless information. Let’s take a look at an example.
Example
Here we have a simple test that is desiring to make sure the URL we used to create the Video object matches the result of calling the playCurrentVideo method in the VideoPlaybackService class. We have created a helper method that allows us to pass in the variables for the Video object creation. However, in most cases we don’t need to have all of the parameters set. In fact, the duration and displayDate have no impact on the current method under test. So we’ve added additional, needless information to the test that makes it more difficult to understand what’s going on.
Solution
We can fix this issue by updating the Video class to adhere more closely to the Builder Pattern so that the additional setting of fields is not needed. Here is the current setter used for the video’s URL.
We can update it to pass back the Video object (this) instead of just being void. Let’s see how this will help to make the test more readable and understandable.
With Builder Pattern
The end result is something much more readable and maintainable. Happy testing!