Archive | October, 2011

The worlds most basic example of Unit Testing

12 Oct

1. In my head, I know what I want a method to do before I even write it, so I write a test that will pass if the code (that I write in step 2) works. In this case it is a basic method in one of my Models.

My fixture has 5 jobs already, I expect the next job to have an ID of 6 and a cost of 18.00

 

2. To make the test pass, here is my REAL method that I add to my model….

 

This just saves the job, the passed arg is an array like the one in the test (or at least I hope it is!)

 

3. Now lets run the test…

 

My test passes - my code does what I had in my head (saves a job)

 

4. Some other guy on the team changes some code…

 

Someone else on the team makes some weird change, probably high on meow

 

5. Looking at the change, it won’t work. The passed arg IS an array, so it will throw an exception. But my original test will catch the fact that this method does not work anymore, otherwise this bug could have gone unnoticed.

 

Before going live with these changes we would run all the tests, in this case, the app doesn't work!

 

From the failed test, you can even see which line of code is failing.

Obviously if you have not written a test for something it can not fail, so being thorough and making sure any bit of functionality has been tested its easy to catch problems and fix bugs.

And if you’re using Git, you can even see who broke the project. Then take it in turns to beat the developer around the head with a blunt instrument.

The worlds most basic summary

Ask yourself “The code I am about to write, what should it do/not do” – then write a test that covers any conceivable eventualities FIRST. Then write the real code to make the test pass.