Magento 2 – Fix Fatal Error ‘Call to Undefined Function’ with __() in Unit Test

magento2phpunit

I am run unit test for catalog module.
There are error display like below in cmd:

Fatal error: Call to undefined function
Magento\Catalog\Block\Adminhtml\Product\Edit\Action\Attribute\Tab__()
in
/var/www/html/magento2/vendor/magento/module-catalog/Block/Adminhtml/Product/Edit/Action/Attribute/Tab/Inventory.php
on line 89

And in Test folder error like below:

Magento\Catalog\Block\Adminhtml\Product\Edit\Action\Attribute\Tab\Inventory->getTabLabel() /var/www/html/magento2/vendor/magento/module-catalog/Test/Unit/Block/Adminhtml/Product/Edit/Action/Attribute/Tab/InventoryTest.php:148

what is the cause of issue for error in magento 2.

Best Answer

It looks like you run this command line without phpunit.xml.dist:
vendor/phpunit/phpunit/phpunit app/code/Magento/Catalog/Test/Unit/Block/Adminhtml/Product/Edit/Action/Attribute/Tab/InventoryTest.php

You need to use phpunit.xml.dist, that contains attribute bootstrap="./framework/bootstrap.php", because this bootstrap file includes BP . '/app/functions.php', that defines global function __()

To run this one test try to use this command line from the magento project root:

vendor/phpunit/phpunit/phpunit -c dev/tests/unit/phpunit.xml.dist vendor/magento/module-catalog/Test/Unit/Block/Adminhtml/Product/Edit/Action/Attribute/Tab/InventoryTest.php

Also look how to Run tests for a specific module in Magento2