Tips for writing maintainable tests
(JP 31/01/2017 originally presented with real test refactor)
Having tests is a pre-requisite for improving them so having imperfect tests is always better than not having test.
Having well factored test allow for easier maintenance, so when writing test we should strive for the following:
- Use sub functions in your tests, in particular, for top level test function (the one registered in test suite) we should:
- Make simple to read
- Keep as short as possible
- Focus on the ‘What’ and ‘Why’
- Use named function to implement ‘How’ if it reduce clarity (member or free function)
- Use member initialized/destroyed in setup/teardown:
- Hide common initialization code
- Provide helper member variable for often used varialble
- Use AAA(Arrange/Act/Assert) Pattern:
- This constrains tests to some simplicity that allow future reader to:
- Understand the intent
- Understand the scope of the tests, and potential gaps in testing
- Update them
- Regular structure also speed up reading/understanding
- This constrains tests to some simplicity that allow future reader to:
Presented at IndigoVision during a training session on 31/01/2017 with supporting code change to our internal code base.
This work by Jean-Philippe DUFRAIGNE is licensed under a Creative Commons Attribution 4.0 International License.