Unit Testing Makes Your Code Better

Greg Ward
http://gerg.ca/

It's for the common good.

Unit Testing makes your code more beautiful. Beautiful is better code.

  • easier to understand
  • easier to extend
  • easier to reuse

A Real Life Case Study

  • Demonstrating how adding tests helps you have better code
  • Better code means simpler tests

Background

  • what is it?
  • why does it exist?
  • where does it come from?
  • what requirements does it meet?

Their code measures the Internet

  • lots of pings
  • lots of traceroutes
  • lots of TSV files

Where to start testing?

  • You can't test an object if you can't construct it, so start with the constructor!
  • The goes double if the constructors does interesting things
  • Write tests to cover all code paths

What did this help with?

  • writing the tests made me look deeper
  • make me read the code very carefully
  • made me see both the good side and the bad side of the code

Gives you the "courage to refactor"

Costs of Not Testing

  • Untested code is buggy code
  • Incorrect code
  • Fear of refactoring
  • Code duplication --> bug duplication
  • Insufficient code reuse

Don't let this get you down!

  • 1000 tests are better than 999
  • 1 test is vastly better than 0 tests
  • unit tests will never cover everything
  • but you'll be pleasantly surprised by how much you can over with some effort

Conclusions

  • tested code is better code
  • writing unit tests makes your code more beautiful