photo credit: binary-code.jpg via photopin (license)

Unit Test your custom module in Magento 2

Magento 2 comes with a great set of unit tests out-of-the-box. You can add these tests to your module as described by Ash Smith in this article, but that means you need to run your unit test with the –filter  attribute like so:

This is great of course, but it still means the entire test suite is loaded and only tests that passes the filter are executed. Now since Magento 2 (finally) has namespaces, this might result in some unwanted results. Say you have a quite generic class name, like Controller  or Product , this would mean that your filter would match all other kind of tests as well. We don’t want that when we want to rapidly program and test side-by-side.

How to test a single class

As you might know, the convention with Magento 2 is to place your unit tests in a folder called Test/Unit  inside your modules’ folder. Now, if we put a phpunit.xml -file inside that folder with the following content:

… we can effectively browser to the folder and execute phpunit  from there (assuming you have PHPUnit installed as a globally executable). Not the bootstrap -argument in the file above. It states that we want to load the bootstrap.php  file from Magento that comes with Magento’s own testing framework. Also note the constant MAGENTO_ROOT , which is a constant required on some places to get the root of Magento.
Needless to say, we can also start our test by executing the following line anywhere on your system:

That’s it! Happy testing everyone!

Visitors give this article an average rating of 4.0 out of 5.

How would you rate this article?

Leave a Reply