If you are a good developer/tester you probably ask yourselves these questions 🙂
- How many tests of each type should I have?
- Do I need to write more unit tests?
- Do I need to have less e2e tests?
Well luckily, we have the test pyramid below that can be used as a guideline for how many tests, roughly, you should have of each type. It is fairly self-explanatory; have a lot of unit tests and very few e2e tests. Why you ask?
Unit tests are cheap in terms of power/CPU usage/processes etc and e2e tests are the opposite. Unit tests give you fast feedback and tell you exactly where an issue is if one occurs. With an e2e test this is much more difficult. Because an e2e test most likely is using all the clients and services (or at least two or three), you have to dig more into the code to figure out what is going on.
The test pyramid also highlights testing strategies. This is called ‘Bottom Up’, i.e.
- Test the domain
- Tests closer to the code
- Integrate early
- Use mocks or stubs
- Visualise test coverage
What is a unit test?
Takes a very small piece of testable code and determines whether it behaves as expected. The size of the unit under test is not strictly defined, however unit tests are typically written at the class level or around a small group of related classes. The smaller the unit under test the easier it is to express the behaviour using a unit test since the branch complexity of the unit is lower.
If it is difficult to write a unit test, this can highlight when a module should be broken down into independent, more coherent pieces and tested individually.
Unit testing is a powerful design tool in terms of code and implementation, especially when combined with TDD.
What can/should you unit test?
- Test the behaviour of modules by observing changes in their state. This treats the unit as a black box tested entirely through its interface.
- Look at the interactions and collaborations between an object and its dependencies. These interactions and collaborations are replaced by mocks/stubs etc.
Purpose of unit tests
- Constrain the behaviour of the unit
- Fast Feedback