Test Driven Development
“Legacy code is any code that does not have tests”
- Jonathan Allen
“The only thing standing between your code and the spaghetti it desires to be, are your tests”
- Alex Mickelson
“The slowest way to check if your program is working is the debugger”
- Heber Allen
“One of the things I have found really valuble for tests is that it makes your code flexible. [With TDD] you have a suite of tests you can run to check if your program works correctly. You are one click away from knowing if you logic was right”
- Diego Vanegas
Terminology
- Unit test - A mini-program that checks the functionality of a unit of code.
- Integration test - A program that checks the combined functionality of multiple units of code
-
TDD - Acronym for Test Driven Development
- Red, Green, Refactor - The TDD lifecycle
- Red: You have a failing test, you cannot implement features/functionality unless you have a failing test. You are only allowed to add minimal code untill your tests pass. Code that does not compile is ‘Red’.
- Green: All your tests are passing. At this stage you are not allowed to add functionality to your code.
- Refactor: Once your tests pass you should refactor your code. Your tests will tell you if you broke something. You are only allowed to change (refactor) existing code, not implement new code.
Common Pitfalls While Testing
- Multiple assertions per test.
- Large iteration loops
- Implementing more than the minimum amount of code
- Making decisions before we need to
Test driven development documents your development process. The initial tests are for the most fundamental code, like a constructor. Here are some of my beggining tests from Kata 14
test "split string by spaces" do
string = "string with spaces"
expected = ["string", "with", "spaces"]
assert expected == BookGenerator.string_to_list({:ok, string})
end