Skip to main content

Unit Testing is an Adventure

If you have spent any time looking at software development you probably ran across something that mentioned testing. The most commonly discussed type of testing you may have found being "unit testing". These aim to test as little of a particular code base as possible making them very fast. I personally write them every day for all of the code I produce. This at first glance seems like it would make my progress slower but as a whole I actually produce better code with tests.

Regression Proofing

First on everyones list of reasons to write unit tests is to prevent future changes from breaking current uses. In very small projects this might be a proportionally small value but any project that lasts more than a few days I have found value in writing tests. I know when refactoring code that it will continue working as expected because the current tests all pass. This builds confidence both in my abilities and in the software I am producing that they are both improving.

Understanding the Language

I took software classes in College, I taught myself a lot of things and learned a lot from the jobs I have loved over the years. Nothing compares to the knowledge I have gained by writing unit tests for the code I write. As you write unit tests you often want to replace the use of third party or library calls with fake versions for speed and to simplify the tests. While trying to fake these things in Python I have learned the insides of classes, functions, modules and a host of things related to built in methods. Most of these things I would be unlikely to learn merely by writing software.

On several occasions this has proved valuable when creating something new. In one case I created a Python testing framework that created test cases from a JSON file describing each scenario. The process of learning how to dynamically add test methods to the classes in a way that the test runner would find them taught me a great deal of the inner workings of Python.

Forcing Smaller Units

Many times I have found myself creating many mocks or having to setup complex data structures to run a particular test. When I step back from the immediate problem the real issue immediately appears: a unit with too much responsibility.

Regardless if a unit is a class or a method if testing that unit is difficult it often means it should be broken up into several smaller units. The more often you write tests the more natural this becomes. As a test becomes more complicated you start refactoring your code to make it easier to use, which is fairly easy because you have tests around it before you start making changes.

Comments

Comments powered by Disqus
Share