Tuesday, June 21, 2011

Unit Tests: How and Why ?

Back in college, we were introduced to unit tests only because our teacher HAD TO and not because he felt it was useful. That's what I felt back then. I remember that he even asked me how could he teach that subject to future students to keep their attention after I told him I wrote batches and batches of tests during my internship.

Unit testing is indeed a tedious task and most programmers, or at least new programmers, don't see the potential in writing tests. Again, back in college, we only wrote them to have a grade, so I guess you have to experience it on the field to understand why it is so important. Though, once you decide to write your test cases, another difficulty shows up: are your tests good enough to prove what you wanted to prove ? In my opinion, experience will answer that.

I will still give my opinion about unit tests and talk about why and how you should write them.

The way I see unit tests is simple: imagine an assemblage of pieces, perhaps a car. Sure the car you buy, new or used, is fully functional, but how can we assert that it is okay and safe to drive this vehicle ? I'm not a mechanic, of course, my first reflex is to be sure that all single parts are in good condition: the engine, the transmission, the carburetor, etc. Like I said, I'm not a mechanic. What I'm trying to say is this: if you aren't sure that every single part of your assemblage works properly
, how can you be sure everything will be fine ? That's what you should have in mind when developing a software. In that situation, the parts are your classes. Now, if you are developing a little helper to ease a daily task or any redundant process at your job or things that falls in the category of helping you, unit tests are not necessary in my opinion. I mostly write them for projects of a certain size.. business or personal.

Here's another example, if I already convinced you, you may skip to the code unless you want to hear my little story. Imagine a guitar, an electric one. Can I really say that my guitar is in good condition if I got fret buzz on specific frets ? If one of my pickup has static noise ? Or if my jack outputs low sound ? No, huh? That's what I thought.

Now a software is the same thing, you want everything to work properly. Mostly because object oriented programming encourages you to reuse code. It also helps you designing your system if you decide to go for test driven development, which is basically writing your test cases before or at the same time as your code (but still before writing your actual code). All this will be clear soon =).

Next post will have code !!