September 29, 2006

Testing 1-2-3... is this thing on?

1.1 What are These Strange Creatures?

I have to say that tests are such a straight-forward concept that it’s actually harder to describe what they are than it is to show you how to do them.

So what are tests?

The Official Answer

Tests are collections of questions and scenarios that provide us (developers) with consistent results which prove that our application is doing what we expect it to do.

The Unofficial Answer

We write tests to interrogate, taunt, bully, punish, and otherwise kick the crap out of our application code until it consistently gives us the correct answer. Think of it as “tough love”. ;)

Need some examples?

* ensure user names have at least 4 characters
* ensure that when we save this record, the administrator is e-mailed
* ensure all replies are deleted when we delete the parent message
* ensure that Canadians have GST of 7% applied to their purchases

The idea of tests is that you write them at the same time as you write your application. In essence, you’re writing two application. As your application grows and becomes more complex, you create many tests. Re-running these tests at any point will help you discover if you’ve “broke” anything along the way.

Some developers actually take this a step further and create the tests before they create the application. This is called Test Driven Development (TDD), and although I personally don’t subscribe to it, it’s a totally legit way of coding.

There’s volumes written about Test Driven Development and testing in general. For more information, talk to Mr. Google.

1.2 So Why Test?

As mentioned before, tests offer proof that you’ve done a good job. Your tests become your own personal QA assistant. If you code your tests correctly, at any point in development, you will know:

* what processes work
* what processes fail
* the effect of adding new pieces onto your application

With your tests as your safety net, you can do wild refactoring of your code and be able to tell what needs to be addressed simply by seeing which tests fail.

In addition to normal “did it pass?” testing, you can go the opposite route. You can explicitly try to break your application such as feeding it unexpected and crazy input, shutting down critical resources like a database to see what happens, and tampering with things such as session values just to see what happens. By testing your application where the weak points are, you can fix it before it ever becomes an issue.

A strong suite of tests ensures your application has a high level of quality. It’s worth the extra effort.

Another positive side-effect of writing tests is that you have basic usage documentation of how things work. Simply by looking at your testing code, you can see how you need to work with an object to make it do it’s thing.

But enough about theory.

FROM: Ruby on Rails

No comments: