Introduction to Test Driven Development

No comments

First off, what do tests provide us with?

  • Documentation code
  • Catch future errors
  • Long-term time savings - because errors have been found before anythings been deployed to production
Although all the above are true, using tests like this is just a tool - not a process.

What is TDD?

In it's simplest form TDD comes down to the following process:
  • Decide what the code will do
  • Write a test that will pass if the code does that thing
  • Run the test, to prove it will fail
  • Write the code
  • Run the test again, to see it pass
It's important to note that you must not write the code, until you've written the test.
Also it is essential to ensure the test actually fails first, it is surprisingly easy to make a small mistake in your test case that means your test will always pass, and that's not the type of error that anyone likely to look into. It's also sometimes necessary to back-test, where you break the code to show that the test fails.
This should be done for every couple of lines of code, every method.

What does TDD provide?

  • Design and plan before you code
  • Documenting your design before you build it
  • Proving that the code implements that design
  • Encouraging the design of testable code - very important!!
Testable code, is good code!
This is because if you have long methods/ functions with loads of if statements and stuff, it's just not possible to write tests. If you write the tests first, you can't write the code that is too complicated.

Testable code is:

  • Modular, as we're forced to break things down so we can test them
  • Decoupled design, if our objects or methods are too tightly interwoven, we can't test them independantly.
  • Methods should have limited scope, and not trying to do too much in one place
  • etc... 
Basically good testable code will have a much lower cyclomatic complexity. This is the measure of how many different paths there are through the code, so essentially every conditional statement you add, will give you another route and another set of tests.

If your finding the test complicated to write, then that's a code smell, your going about it the wrong way.

Result of TDD

Better code in less time *

*so it might not feel like it's going faster, because it's a process rather than just hacking. And processes feel tedious. Also it may take some practice to get up to speed, but it's fully worth it in the long run for speed and code quality.

Use your judgement about when to test

Although nearly all code should be tested thoroughly there are some exceptions:
  • Some things are too hard to test - especially where external services are involved
  • Some tests are too trivial to be useful
  • Over-testing is possible 
  • Exploritory codeing, whern your not sure how it's going to be used. SO not for production code.

Links for learning more about TDD

No comments :

Post a Comment