Unit Test Implementation in custom module in Magento 2

I have written this blog post to help those who are new at writing unit tests and how to write basic unit tests for your Magento 2 custom modules. Magento 2 comes with a great set of unit tests out-of-the-box. Magento 2 comes pre-installed with PHPUnit, an automated testing framework for PHP that has been included as a dependancy in Magento 2’s composer.json.

Today I'm going to create a small custom module in magento 2 and will write test cases for it. Let’s start, now I am assuming that you are aware with the Magento Directory structure and know how to create custom module. Let me brief I am going to create a model for calculator where we can perform basic operations like addition, substraction etc.

Step 1: First create your custom module and register it, here I am creating a module named "Prashant_HelloUnitTest".

Step 2: Create model calculator here :
app/code/Prashant/HelloUnitTest/Model/Calculator.php

<?php
 
namespace Prashant\HelloUnitTest\Model;
 
class Calculator {
    /**
     * this function will perform the addition of two numbers
     *
     * @param float $a
     * @param float $b
     * @return float
     */
    Public function addition($a ,$b) {
        return $a + $b;
    }
}

Now lets create unit test model for the above.

Step 3: Create test model here :
app/code/Prashant/HelloUnitTest/Test/Unit/Model/Calculator.php

<?php
 
namespace Prashant\HelloUnitTest\Test\Unit\Model;
 
class Calculator extends  \PHPUnit\Framework\TestCase {
 
    protected $_objectManager;
    protected $_desiredResult;
    protected $_actulResult;
    protected $_calculator;
    /**
     * unset the variables and objects after use
     *
     * @return void
     */
    public function tearDown() {
         
    }
 
    /**
     * used to set the values to variables or objects.
     *
     * @return void
     */
    public function setUp() {
        $this->_objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this);
        $this->_calculator = $this->_objectManager->getObject("Prashant\HelloUnitTest\Model\Calculator");
        //can do stuff
    }
    /**
     * this function will perform the addition of two numbers
     *
     * @param float $a
     * @param float $b
     * @return float
     */
    public function testAddition() { 
         $this->_actulResult = $this->_calculator->addition(7.0,3.0);
         $this->_desiredResult = 10.0;
         $this->assertEquals($this->_desiredResult, $this->_actulResult);
    }
}

Step 4: Run below command and check output.

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