close

How To Write Test Cases For Unit Testing In Magento 2?

Post by|Magento25 November,2020
2043 View

Unit test cases are useful to validate pieces of code. Magento 2 provides PHPUnit and a testing framework for PHP. Magento covers various testing methods to make sure that the code quality is at par with the quality standards. Code quality matters with the end-user working with the store front end for the better user experience and expected results.

Benefits Of Unit Testing In Magento 2

Every developer has the same question. Why should I test my code? Isn’t it a waste of time? Sometimes magento developers skip the process of unit testing to save time, which may lead to more quality issues . So before we start writing test cases, let’s discuss what the benefits of unit testing are.

  • Find errors early before going to production.
    By doing the unit testing, we can find common errors and correct the process’ flow before we move to production.
  • Upgrade platform
    By writing a test case, we can make sure the module functionality, and it will also help when the system upgrades and your module works with the updated system.
  • Design
    Design is one of the critical factors for e-commerce websites. Before writing the test cases, you only need to think about the design, and you can easily overcome upcoming responsive issues.
  • Reduce the cost of change
    If your product is up-to-date with Magento standards with proper test cases, it will be easy for developers to quickly inject new features and reduce the cost of the change.
  • Save time
    Regular unit testing will reduce the number of errors for QA and Developers and, overall, reduce the time of back and forth testing.

Writing The Test Cases For Unit Testing

You can write the test cases within your module so first of all, we will create a custom module to write test cases. For the testing purpose, we are using Zealousweb as a vendor and UnitTest as a module name.

Step 1

Create module.xml file under app/code/VENDOR/MODULE/etc and add below code.

<?xml version=”1.0″?>

<config xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:noNamespaceSchemaLocation=”urn:magento:framework:Module/etc/module.xsd”>

  <module name=”Zealousweb_UnitTest” setup_version=”1.0.0″ />

</config>

Step 2

Create a registration.php file to register your module. Place file under app/code/VENDOR/MODULE/

\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
‘Zealousweb_UnitTest’,
__DIR__
);

Step 3

Now we will create a simple Magento module and write test cases for the same module. You can use your model if you already have it in your extension.

Create model Calculator.php under app/etc/VENDOR/MODULE/Model

namespace Zealousweb\UnitTest\Model;
class Calculator {
public function add($value1, $value2) {
$total = $value1 + $value2;
return $total;
}
}

Step 4

We need to create a Test file for the Model Calculator.php. Before we write test cases, it is essential to know that we should implement a setup and tearDown method in our test file. The setup method will be executed before the test runs, and the tearDown method will be executed after the test is completed.

Now, if we are creating a test method for the “add” function of the model. It is required to have a test word before the test method name. So our method name for the test case would be “testAdd.” Below is an example of the test class.

As per the naming conventions, we will put our unit test under the Test/Unit folder.

<?php

namespace Zealousweb\UnitTest\Test\Unit\Model;

class TestCalculator extends \PHPUnit\Framework\TestCase {

    protected function setUp() {

        $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this);

        $this->model = $this->objectManager->getObject(“Zealousweb\UnitTest\Model\Calculator”);

    }

    public function tearDown() {

/* Perform action after the test run */

    }

    public function testAdd() {

        $result = $this->model->add(10, 5);

        $expectedResult = 15;

        $this->assertEquals($expectedResult, $result);

    }

}

You can also define the multiple test methods in the same test model.

Executing The Test Cases For Unit Testing

After the implementation, it is necessary to run the test. There are multiple ways to run the test.

CLI

The client method for execution will run only a single test file. Here you need to define the file path and run the below command from the Magento root.

php ./vendor/bin/phpunit -c dev/tests/unit/phpunit.xml.dist app/code/Zealousweb/UnitTest/Test/Unit/Model/Calculator.php

Magento Commands

Magento commands will help you to execute all the tests written by Magento and by you. You need to run the below command from the root of Magento.

php bin/magento dev:tests:run unit

PHPStrom

This process is a little lengthy. IDE integration is required to run the test using PHPStrom. Magento comes with the file named phpunit.xml.dist, which resides under dev/tests/unit/phpunit.xml.dist. By using this file, PHPUnit knows where to test cases.

Rename this file to phpunit.xml from phpunit.xml.dist and define you Model Class in the directory below

../../../Zealousweb/UnitTest/Test/Unit

Now PHPUnit can find your test, and now you will be able to run the test from Toolbar > Run > Edit Configuration.

Conclusion

Here we discuss how we can write test cases and how we can execute the test. Unit testing might be a complicated process if you are not familiar with PHP Unit. It is always a good idea to take reference to core modules in such cases.

Unit testing saves time and avoids errors in Magento development before going to production. There are many more assertions you can find in Magento’s core modules. If you are a newbie, I would recommend reading documentation over the PHPUnit. Happy Testing.

FAQ

Can we only check Equal values in test cases? How can we check boolean values?

To check the boolean value, you can use “assertTrue” or “assertFalse.” You also have options like assertNull, assertNotNull, assertIsA, etc. You can find more assertions in the Magento modules.

Can we use another module or helper in the test class?

Yes, you can define them in the setUp method and use them as per the need.

I am facing an issue of the allowed memory size of 67108864 bytes exhausted. How do I resolve it?

 You must have the file dev/tests/unit/phpunit.xml.

Find the “xdebug.max_nesting_level” and add below next after this.

<ini name=”memory_limit” value=”-1″/>


Speak Your Mind

Please enter your comment.
Please enter your name.