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

ZealousWeb
4 min readNov 26, 2020
How To Write Test Cases For Unit Testing In Magento 2?

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.

Originally published at https://www.zealousweb.com.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

ZealousWeb
ZealousWeb

Written by ZealousWeb

Helping businesses Solve The Unsolved with a tech-first approach to expedite digital transformation.

No responses yet

Write a response