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.

Understanding the structure and components of a unit test case in Magento 2

Here are the key components to consider:

  • Test Class: A class containing the test methods and assertions.
  • Test Methods: Individual methods within the test class, each representing a specific test case.
  • Fixture Setup: Preparation steps to set up the required environment for the test, such as initializing objects or loading data.
  • Test Execution: Invoking the method being tested and capturing the results.
  • Assertions: Statements that validate the expected outcomes or behaviour of the code under test.
  • Teardown: Cleaning up the environment after the test completes, restoring the initial state.
  • Annotations: Optional annotations to configure specific test behaviours or dependencies.
  • Test Suite: A collection of test classes or methods to be executed together.

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″ />

Step 2

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


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.

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.


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


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


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

Best practices for writing effective unit test cases in Magento 2

Here are some key pointers:

  • Test Single Units: Ensure that each unit test focuses on testing a single functionality or method in isolation, avoiding dependencies on other modules or external resources.
  • Use Descriptive Names: Give your test cases meaningful names that clearly indicate their purpose and the specific functionality being tested.
  • Maintain Test Independence: Make sure each test case is independent and doesn’t rely on the state or output of previous tests.
  • Incorporate Data Providers: Utilize data providers to supply various input combinations to test different scenarios effectively.
  • Test Edge Cases: Cover edge cases and boundary conditions to validate the behaviour of your code in critical situations.
  • Use Assertions: Include relevant assertions to verify the expected outcomes of your tests, comparing actual results against predefined values or conditions.


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.