Reading list Switch to dark mode

    PHP Unit Test in Magento Open Source

    Updated 27 April 2023

    As a Magento Open Source Developer, you should have to write Unit Tests for the modules to validate the code is errorless and bug-free.

    What is Unit Testing in Magento Open Source?

    Unit Testing is a crucial operation, a set of the smallest testable parts of an application, which are called units, in the development of software. The unit testing will ensure that the codes you wrote are running correctly as well as raise the software quality you created before. In addition, remember that the unit testing process is separate and completely automatic without any manual handling.

    Why Unit Test?

    The main objective of Magento Open Source unit testing is to isolate written code to test and determine if it works as intended. Unit testing is an important step in the development process because if done correctly, it can help detect early flaws in code which may be more difficult to find in later testing stages. The unit test plays a role in improving the manageability like:

    • Tests Reduce Bugs in New Features
    • Tests Reduce Bugs in Existing Features
    • Tests Are Good Documentation
    • Tests Reduce the Cost of Change
    • Tests Allow Refactoring
    • Tests Constrain Features
    • Tests Defend Against Other Programmers
    • Testing Makes Development Faster

    For creating Unit Tests don’t forget you’ll find the Unit Test in app/code/[Vendor]/[ModuleName]/Unit/Test

    How to run Magento Open Source Unit Test?

    In the below example of helper the unitTest function is defined which returns some value. We are going to test it through Unit Test.

    Searching for an experienced
    Magento 2 Company ?
    Find out More
    <?php
    namespace Webkul\UnitTest\Helper;
    
    use Magento\Store\Model\StoreManagerInterface;
    
    class Data extends \Magento\Framework\App\Helper\AbstractHelper
    {
        /**
         * @var StoreManagerInterface
         */
        protected $storeManager;
    
        /**
         * @var \Magento\Framework\App\Helper\Context
         */
        protected $context;
    
        /**
         * __construct function
         *
         * @param StoreManagerInterface $storeManager
         * @param \Magento\Framework\App\Helper\Context $context
         */
        public function __construct(
            StoreManagerInterface $storeManager,
            \Magento\Framework\App\Helper\Context $context
        ) {
            parent::__construct($context);
            $this->storeManager = $storeManager;
        }
        
        /**
         * Unit Test method
         *
         * @return string
         */
        public function unitTest()
        {
            return __("This is Unit Test");
        }
    }

    Create a Unit Test file: app/code/Webkul/UnitTest/Test/Unit/Helper/DataTest.php

    <?php
    namespace Webkul\UnitTest\Test\Unit\Helper;
    
    use Webkul\UnitTest\Helper\Data;
    use Magento\Store\Model\StoreManagerInterface;
    use Magento\Framework\TestFramework\Unit\Helper\ObjectManager;
    
    class DataTest extends \PHPUnit\Framework\TestCase
    {
        /**
         * @var StoreManagerInterface
         */
        protected $storeManager;
    
        /**
         * @var \Magento\Framework\App\Helper\Context
         */
        protected $context;
    
        protected $expectedMessage;
    
        /**
         * Set up
         *
         * @return void
         */
        protected function setUp(): void
        {
            $objectManager = new ObjectManager($this);
    
            $this->context = $this->createMock(
                \Magento\Framework\App\Helper\Context::class
            );
    
            $this->storeManager = $this->getMockForAbstractClass(
                StoreManagerInterface::class
            );
    
            /* Mock Class Object With Constructor Args*/
            $this->helper = $objectManager->getObject(
                Data::class,
                [
                   "context" => $this->context,
                   "storeManager" => $this->storeManager
                ]
            );
        }
    
        /**
         * Test unitTest function
         */
        public function testUnitTest()
        {
            $this->expectedMessage = __("This is Unit Test")
            $this->assertEquals($this->expectedMessage, $this->helper->unitTest());
            // Optionally
            $this->assertTrue(true);
        }
    }

    Running Unit Tests in the CLI

    For running all Unit Tests

    vendor/bin/phpunit -c dev/tests/unit/phpunit.xml.dist

    Running only a subset of the unit tests

    To run only tests within a specific directory branch, all you have to do is to specify the directory branch after the command.

    vendor/bin/phpunit -c dev/tests/unit/phpunit.xml.dist          app/code/Webkul/UnitTest/Test/Unit/

    You’ll run the above command from Magento Open Source root then it will display the test result.

    PHPUnit 9.5.20
    
    ...........                                                                                                                        1 / 1 (100%)
    
    Time: 00:00.171, Memory: 34.00 MB
    
    OK (1 tests, 1 assertions)

    This is the basic introduction to Unit Testing in Magento Open Source and Adobe Commerce. In the next blogs we will discuss the below points:

    Thank’s for reading this. If you have any queries please comment below.

    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    2 comments

  • Rahul
    • Saurav Kumar (Moderator)
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home