Magento 2 Development Unit Testing.
18 August 2019
Magento 2 Unit Testing is a very important aspect of Magento 2 Development, especially if you’re a module developer.
This article will help you understand how Magento 2 Unit testing can be done.
I wrote a small module to explain the testing. Consider an Event Observer use. Let’s assume you need to run an observer in checkout. With a unit test you can run the observer without going to the front end and avoid all the hassle of swapping between frontend and backend for testing.
Instead you write the Observer and test it in the command line then you can just do the final test in the Magento front end.
For easy an explanation I wrote an Observer for controller_action_predispatch
First write your events.xml in etc folder and create Observer at the Module Observer folder
If you look at
public function setup()
Using
$this->getMockBuilder('Magento\Framework\App\RequestInterface')
you can create observer parameters to pass to the test observer
You can use Magento ObjectManager, if you need to create any objects in your Magento unit test file.
Likewise you can call any instances either using Object Manager, or directly using namespace.
Functions testGetTextTo
and testMainSpace
in this case it doesn’t have complex logic. But you can use as many test functions as you need.
Next let’s write our unit test.
The unit test goes inside the Test/Unit
folder of your module. Since our example is an Observer you need to create the Observer folder inside of the Unit folder and include the Observer test file.
Test/Unit/Observer/ControllerActionPredispatchObserverTest.php
That’s It. Now you can run the Observer test file from Command line.
Open your command line tool and run the test file
/dev/tests/unit ../../../vendor/phpunit/phpunit/phpunit ../../../app/code/Forgeonline/Unittesting/Test/Unit/Observer/ControllerActionPredispatchObserverTest.php
You don’t need to install PHP Unit Test if you run the above code. Browse to your /dev/tests/unit
folder and run phpunit test library.
If the test was successful you will see the success message.
You can download the example from Github
More about Magento 2 Development Unit Testing
Find out more about PHP Unit Testing
Forge Magento Website development