Unit Testing Definition:
— UNIT TESTING is a software development process where individual units from a functional(programming) file or components of the software are tested automatically using code level.
— Main Intention for a Unit test is to validate each unit of the software performs as logic designed.
— The unit testing process is completely automatic without any manual testing for functionality.
Magento 2 comes with pre-installed PHPUnit library, an automated testing framework for PHP.
You can see the library at the root of Magento installation with vendor/phpunit folder. A phpunit is included as the dependencies in Magento. You can check the dependencies in composer.json with a required-dev section.
You can check the basic functions related to phpunit from official PHPUNIT site.
Prerequisites to test Unit Test:
The Magento_Developer module must be enabled in Magento 2. Default Magento Developer module is already enabled with Out of the box.
Benefits of Unit Test:
— Quality of Code (You can trust the coding standard for your code are fully tested.)
— Find Software bug in an early stage. (at development time you can find the bug from coding if you have)
— Design (For Unit test write, You need to understand your flow of design accurate. Testing the smallest piece of code forces you to define what that code is responsible for the design.)
— Debugging Process (Debugging becomes simple if your Unit Test failed)
— Cost Reduce (You can reduce your future cost for development due to your code is tested with Unit Test and less probability to get a bug in future of already tested code.)
Command to run Unit Test:
1. Test all the Unit test in Magento Core modules:
php bin/magento dev:tests:run unit
2. If you want to run a unit test for a specific module, you need to run below command,
Let’s you need to run for CMS module Unit test,
php vendor/bin/phpunit -c dev/tests/unit/phpunit.xml.dist vendor/magento/module-cms
3. File Specific Unit Test,
If you want to run PostDataProcessorTest.php file Unit Test from CMS Module,
php vendor/bin/phpunit -c dev/tests/unit/phpunit.xml.dist vendor/magento/module-cms/Test/Unit/Controller/Page/PostDataProcessorTest.php