Unit testing is a key testing component in the development lifecycle. It is used to test modules of code in isolation to ensure that the individual module code and each unit test is separate to other unit tests.
Example piece of code:
Example of basic unit test:
In real world scenarios, there would be many different valid and invalid phone numbers, these could also be added and then simply running this test will verify if the logic used to verify a phone number is valid.
Unit testing is an important first layer of testing as it will catch any issues with the underlying code and can be performed automatically at the time of building the project, so after each change to the source code, all of the unit tests are run to capture any issues with existing code and functionality. This makes it a really effective tool to utilise in an agile environment and provides unit testing the ability to be at the centre of agile testing since it will help eliminate basic levels of bugs and reduce the cost of these.
Tips for Unit Testing
- When refactoring your code, you should unit test it accordingly. Not only do you need to add new methods into the components, you also need to perform corresponding tests.
- For each bug that is to be fixed, a corresponding unit test should be written to test for this bug so in future releases this bug can be ensured not to crop up again. If it does re-appear, the unit test should capture this and a fix can be made
- The main goal of unit testing is to provide confidence in the code
- When writing unit tests, aim to test towards a single component instead of writing more functional tests. This means the major components will end up having their own suite of tests
- Make unit tests simple and focused on the core behaviour. This makes them easier to maintain and cuts down on the time required so developers will be more likely to write them
- Ensure unit tests have names which describe the subject, scenario and the result of the test. This will be advantageous when test suites grow and comes in handy for maintenance.
In summary, unit testing can really help in agile development methods, and in truly agile environments it is absolutely necessary to have good unit testing practices and coverage since agile environments will often have changes adapted into the product, so a thorough unit test suite that is automated will ensure that less bugs are created as a result of these changes saving both time and money while providing a more stable product.