Installing PHPUnit
To globally install the Phar, following the commands as below:
$ wget https://phar.phpunit.de/phpunit.phar $ chmod +x phpunit.phar $ sudo mv phpunit.phar /usr/local/bin/phpunit #testing the phpunit $ phpunit --version
Creating a Magento test case
Unit testing is a key part of Test Driven Development (TDD). With TDD, we will write the test case first, and then we will write the code that returns the expected values that we defined in the test case.
With Magento, which is based on the Zend Framework and build with TDD, it is possible to write unit tests with PHPUnit for a custom or existing module.
In this tutorial, we will create a unit test for the Jeff_Helloworld module that we created previously, Creating Your Own Event In Magento.
Following these steps to create a unit test for Magento:
- Create a folder named unit-tests in your Magento root.
- Create an autoload.php in the unit-tests folder.
- Open the autoload.php file and add the following content in it:
-
Create a phpunit.xml fine in the unit-tests folder with the following content:
./ ../app/code/local -
Create a folder tree in the folder unit-tests with command:
mkdir -p app/code/local/Jeff/Helloworld/Model -
In the folder app/code/local/Jeff/Helloworld/Model/, create a new PHP file called SubscriptionTest.php, and add the following content:
getName(); Mage::app('default'); $this->_subscriptionInstance = Mage::getModel('helloworld/subscription'); } protected function tearDown() { } public function testGetAllSubscription() { $subscriptions = $this->_subscriptionInstance->getCollection(); $this->assertInstanceOf('Jeff_Helloworld_Model_Resource_Subscription_Collection', $subscription); } } -
To start the unit test, open the terminal and navigate to the unit-tests directory with run the phpunit command. You will see some message about the Unit Test results.
OK (1 test, 1 assertion).
Some Explanations
The bootstrap of the phpunit command is configured in the phpunit.xml file. In this file, at the beginning of the command, we can configure some parameters that are important. In the phpunit.xml file, we configured the autoload.php file first in order to run it. In this file, we set the include path with path of the Magento application, some PHP settings, and the inclusion of the Mage.php file.
The unit test itself is written in the SubscriptionTest.php file. In this file, we created a class that extends the PHPUnit_Framework_Testcase class. This parent class contains all the logic for the unit test and the generic functions.
In the setup() function, we can write some code to bootstrap the test. The unit test is in the testGetAllSubscriptions() method. The phpunit command will run all the test* functions in that class. In this function, we used the function assertInstanceOf() to see if the type of the class matches the value that is set in the first parameter.