Writing unit test should be essential task each developer should proceed. Unit tests give you confidence your code runs as expected and doesn't break anything else.
Magento 1 is still being used by many merchants and although it's complexity is not as large as for Magento 2, writing unit tests should be apart of any development. Following recipe targets majority of developers:
- your IDE is PhpStorm
- your Magento 1 runs in Docker container
Install PHPUnit
In your project root type following command:
composer require phpunit/phpunit
If you do not use composer for your project, this will create composer.json
and place all required files into vendor
folder.
Create PHPUnit configuration
Paste following XML into the project root:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="vendor/autoload.php"
colors="true"
verbose="true"
stopOnFailure="false">
<testsuites>
<testsuite name="Your Test Suite">
<directory>tests</directory>
</testsuite>
</testsuites>
</phpunit>
This piece of XML instructs PHPUnit to look for tests from your test suite in tests
folder. Feel free to change it accordingly.
Write your test
Inside your tests
folder create your first test:
<?php
// path to your Mage file
require_once '/var/www/html/app/Mage.php';
// path to the file you want to test
require_once '/var/www/html/app/code/local/YourVendor/YourModule/Helper/Whatever.php';
class TestFirst extends \PHPUnit\Framework\TestCase
{
public function testGetSomeResponse() {
Mage::app();
$helper = new YourVendor_YourModule_Helper_Whatever();
$this->assertEquals($helper->getSomeResponse(), 'Your result');
}
}
That's the very basic backbone of unit testing setup (and the minimal viable one). Now it's time to run your tests in your IDE.
Click on green play symbol next to public function testGetSomeResponse()
or next to class TestFirst extends \PHPUnit\Framework\TestCase
. This will
trigger the test run.
All the configuration of PHPUnit will work as normally as the phpunit.xml
is present and might (and should)
be used to be tuned according to your preferences
Now let get your hands dirty, happy coding!