3 Unit testing: delivering code that works

 

This chapter covers

  • Why unit tests are important
  • What parts of your codebase to test and what parts to ignore
  • How to test your code using dependency injection, mocks, stubs, and more
  • When to create the tests during the development workflow

Unit testing is one of those tasks that all junior developers are assigned, especially when they first join an existing project. It is expected that they get familiar with the source code as soon as possible. The problem, though, is that the purpose of unit testing is to provide security and certainty over the stability of your code so you know it’s bug-free after you change it. Unit testing is not intended to help you understand a codebase. Furthermore, a junior developer entering a team is not the ideal person to write these tests. They don’t know the code or the features they’re testing, so how can they truly cover every use case and edge case?

3.1 Why unit test your code?

3.1.1 What about using unit tests today?

3.2 What to test

3.2.1 Test one thing at the time

3.2.2 Make sure you test a unit of code

3.2.3 Only test your own code

3.2.4 Don’t test external calls

3.2.5 Stick to testing what’s on the rug

3.3 How to write your tests

3.3.1 Your new best friend: Dependency injection

3.3.2 Tame the big four: Mocks, stubs, spies, and dummies

3.3.3 Unit tests are not meant to be run manually