TDD

  • TDD steps: Red (when we have failed tests) > Green (all tests are good) > Yellow (refactoring existing code, could imply some failed tests for a while, don’t add new behaviour here!)
  • Separate the three parts of a test; it should be easy to identify each one. Those parts are: Set, Execute, and Check.
  • Always do the smallest step possible, that requires the minimum number of changes to get green.
  • Each new test should fail, don’t add a test that is green. That means that you are testing something already tested, and that also could mean that you have chosen an invalid order of tests or that you have added too much code in the class that we are testing. So you should do the minimum code, no more.
  • If you are adding a new test, and this requires modifying code that is going to make other tests fail, comment out the new test and apply the changes until the old tests are good.
  • Unify similar tests when possible, using tools like Parameterized in Java, DataProvider in PHP… we also refactor our tests.
  • Don’t abuse assertTrue and assertFalse; they don’t give a lot of information about which values are not good.
  • Don’t test a business rule if you don’t understand it, ask business first.
  • Only apply a refactor if that simplifies our code; if it’s adding more complexity, wait as much as possible, probably some new business rule will guide us.
  • If you have to test invalid cases, take the ones that just don’t follow one of the rules.
  • Do the refactor as fast as possible; when the complexity is bigger it is much harder.
  • Use descriptive test names.
  • Each test just has to check one rule, not more. This implies having, if possible, just one assert. If you have more, ask yourself if you could split it into two tests. So each test should have only one reason to fail and if one assert fails it is not going to hide the others.
  • Test all known limits. Ex. quality decreases by 1 each day, after expiration date decreases by 2. Important to test on the expiration date and after. For that, we could use mutation testing.

Test Doubles

Fakes

They behave as the real ones but taking some shortcuts.

Mocks

Objects that register their usage so we can check before (with expectations) or after (with spies) what they have done.

Stubs

Objects with predefined data.