Magento 2 Development Unit Testing
Magento 2 Unit Testing is a very important aspect of Magento 2 Development, especially if you are 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 unit test you can run the observer without going to the front end and escape with all the hassle.
Instead you write the Observer and test it in command line then you can test the final test in the Magento front end.
If you look at
public function setup()
$this->getMockBuilder('Magento\Framework\App\RequestInterface') you can create observer parameters to pass to test observer
You can use Magento ObjectManager, if you need to create any objects in your Magento unit test file.
Like wise you can call any instances using Object Manager or directly using namespace.
testMainSpace in this case dosen’t have complex logic. But you can use many test functions as you need.
Next let’s write our unit test.
Unit test goes inside
Test/Unit folder of your module. Since our example is an Observer you need to create Observer folder inside Unit folder and include Observer test file.
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 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.