Skip to main content

Magento - Unit Testing


Magento 2 comes with default unit testing in built. But, for magento 1, it is very difficult to perform unit testing. There is an extension EcomDev_PHPUnit, which can help us in performing unit tests in magento 1.

You should have already installed phpunit before installing the ecomdev extension. Install the extension EcomDev_PHPUnit from the git repo.After ecomdev_phpunit installation, two files will be created automatically.
{magento root}/phpunit.xml.dist
{magento root}/app/etc/local.xml.phpunit

Go to root folder and run the unit tests, which will create the tables in the magento test database and then execute the unit tests defined in the modules.
phpunit

The settings are taken from the phpunit.xml.dist. If you want to change the default settings, create phpunit.xml and make changes.

Now we would like to create unit tests for our module. Go to your module code folder and create a Test folder.
{VendorName}/{ModuleName}/Test

Open etc/config.xml and register the phpunit for the module.
....
<config>
.......
    <phpunit>
        <suite>
            <modules>
                <VendorName_ModuleName />
            </modules>
            <!-- optional, to execute the group tests -->
            <groups>
                <lib>{GroupName}</lib>
            </groups>
        </suite>
    </phpunit>
</config>

Create the unit test for our module. We are going to create a test function in Test/Model/BasicTest.php. You can get the test formats from the phpunit website.
<?php

class VendorName_ModuleName_Test_Model_BasicTest extends EcomDev_PHPUnit_Test_Case {

    /**
     * @test
     * @return VendorName_ModuleName_Model_Observer
     */
    public function checkClass() {
        $observer = Mage::getModel('vendorname_modulename/observer');
        $this->assertInstanceOf('VendorName_ModuleName_Model_Observer', $observer);
        return $observer;
    }

}




Comments

Popular posts from this blog

Magento 2 - Create Attributes in Setup

Sometimes in our module we require to create product or category attributes automatically on module install. Also, we might require to add extra fields to quote, sales order, invoice, creditmemo tables. We will go through how to do that in magento 2. You can find the sample code in the git repo .