Unit Testing
Unit testing is testing basic individual units or components of software to ensure that they performing according to the designed specifications. Simply, A unit is a small piece of code for any single function.
Unit tests are done by the developer. It helps to identify whether there are any loopholes in developed code before moving to QA testing.
AAA Pattern for Unit Testing
This is a very important and fundamental idea of unit testing. In simple words, each unit test has 3 processes. Arrange, Act, and Assert.
Arrange
Here, arrange the test by creating necessary objects, setting up mockups, and potential expectations.
Act
This is the invocation of the method being tested.
Assert
Check whether the expectations were met.
Why We Do Unit Testing?
- Reduces development time
The unit test causes to spend less time for debugging and revalidating after code changes. - Identifies defects at early stages
Defects can identify before the code deploy and which reduces the costs of fixing them in later stages of the development cycle. - Gives a better idea about the development
The state of the system can be measured easily once all the unit tests have been run. These tests give developers insight into evaluating other parts of the code, such as whether it is complete or is still under development.
Best Practices of Unit Testing
- Maintain unit tests properly
When the code changes, tests often need to be updated and possibly debugged as well. - Keep them readable
It should be readable to other developers as well. Should keep in mind to name unit tests properly. - Unit tests should verify a single-use case
Good tests validate one thing and one thing only, which means that typically, they validate a single use-case. Tests that validate more than one thing can easily become complex and time-consuming to maintain. - Unit tests should be isolated
A unit test should be runnable in any machine and they should not involve multi-threading, file I/O, database connections, web services. - Unit tests should be automated
It is better to automatically execute unit tests once a particular time period or in CI/CD to review and to aware of actions that can take about code coverage, performance, etc.