What Unit Testing Tells You About Your Code

josepheames

Joe Eames

Posted on June 22, 2020

What Unit Testing Tells You About Your Code

We often focus on the straightforward benefits of unit testing.

  • Verification of working code
  • Verification of correctness of algorithms
  • Edge case testing
  • Regression bug protection
  • Code Documentation

But when we focus just on these surface-level benefits of our code, we miss out on a great opportunity to look a bit deeper.

One of my favorite benefits of unit testing is what I call the GRAND THEORY OF UNIT TESTING or maybe the GRAND UNIFICATION THEORY OF UNIT TESTING…haven't settled on a name yet for this, but I'm accepting submissions.

The theory (which I didn't invent, I'm just trying to name it) is basically this: Code that is hard to test is not good code. Although the inverse isn't necessarily true.

Let's consider some examples:

Example 1: Know that 2000 line pile of spaghetti code that runs the core of your system. Everyone on the team is afraid to touch it, and discussions of refactoring it are similar to discussions of curing cancer and campaign reform? Great idea, but nobody really believes that it's gonna happen. Guess what that code doesn't have? Unit tests. Why? Because every time someone tries to write unit tests around it, they eventually throw up their hands in surrender.

Example 2: You are going to test a class, but that class takes in eight different collaborators in its constructor. Creating mocks for all those different dependencies is SO PAINFUL…. Yup, you've found confirmation of the theory. It's hard to test and it's also poorly written code. If you are taking in eight dependencies, then your class is just doing too much. I've written about this specific code smell previously.

Even if you don't know what every code smell is, your unit tests are essentially a bloodhound you hire to sniff through your code, stopping and pointing at places where you need to take a look.

This also gives us the opportunity to refactor based on our unit tests. If it's hard to write a unit test for something, then take the time, and refactor the code to make it easier to test. You'll most likely end up with much better code than when you started.

Happy Coding!

Enjoy this discussion? Sign up for our newsletter here.

Visit Us: thinkster.io | Facebook: @gothinkster | Twitter: @gothinkster

💖 💪 🙅 🚩
josepheames
Joe Eames

Posted on June 22, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related