As a developer, you have almost certainly already run hundreds of unit tests on your code. That is why this week we are taking a look at a method that helps you organise your tests and reduce the number of bugs: TDD.
Unit tests and TDD: what are the differences?
A unit test makes it possible to check a specific part of the code (generally a function within an object or a module). If the test is specific to that same function, it will be simple and quick to write and to run.
The more unit tests you write, the more bugs you detect in your code: that is why running as many unit tests as possible is very important. You can integrate your unit tests into your code using “xUnit-style” syntax, but contrary to popular belief it is not mandatory — you can also run your tests with a simple function in JavaScript, for example.
TDD, which stands for Test Driven Development, is a working method that consists of designing the tests before writing your code. TDD is carried out in 5 steps:
- Write a test
- Run that test and all the others to see whether they fail
- Write the appropriate code to make the test pass
- Check that the test passes
- Improve the code while keeping the same functionality
This method makes your code valid in all circumstances!
So should you stick with unit tests or opt for TDD? Well, taking the time to write your tests before coding will stop you running dozens of unit tests needlessly. TDD is therefore a more effective method for the smooth running of your project.
To sum up, unit tests are useful for testing parts of your code whenever that seems necessary. However, practising TDD will allow you to organise your tests in advance, and therefore to define — even before writing any code — the number of tests that will genuinely be useful to you. If you would like to find out more about TDD, we recommend watching the meet-up we hosted on software craftsmanship with the help of Michaël Azerhad ;).