Unit Tests

In my day job I work with a large team of developers. Project demands often require a rapid developement schedule which often means low quality code gets submitted in order to hit a deadline; incurring technical debt. Now, regardless of your opinions on this, at some point someone will need to interact with that code. They’ll immediately have a few questions:

  1. What does this do? Does it look bad because it’s a workaround for something I don’t know about?
  2. Does it look bad because it is bad?
  3. Am I going to break something if I change this?

#1 is technically two questions but they kind of resolve to the same thing. Hopefully there’s a comment that provides the context but don’t count on it.

Here’s a place where unit tests are incredibly useful. With good unit tests, if you’ve identified the input and the result you can have a lot of confidence that the code you’ve written is not going to break in production. Sure, there are exceptions. For a start, like everything in programming, testing only covers the cases you thought about. It’s a good argument for keeping testing in mind when writing code as it encourages keeping your methods small and single-purpose. Even if you’re not writing tests up front you might have cause to later (or someone else will have to, and there are few things so fun as having to refactor someone else’s 500 line super method).

So you have the code you need to change. You need to know it won’t break after you make your changes, and if you’re fixing something it’d also be good to validate that it worked without having to try and repro some weird case within the app itself. So, identify the range of inputs and the expected results. Write the test cases. If you have a bug and know the cause the chances are you can write a test for that. Get the tests done up front and validate the existing code first. Now, fix and/or refactor the original code. You’re free to change it and you know your unit tests will give you an early warning that something went wrong without having to compile and run the whole app to get to the specific problem.

Unit tests are not a magic bullet. They are not a substitute for testing the app. They are another tool to help you be confident with your code.