I am following Vinai Kopp's Series on Mage2CodeKata but it gives me an error message when I declare the $objectManager. After seeing these treads:
- Object Manager in Unit Testing in magento 2
- Magento 2: Fixing Call to Undefined Method Mock_BlockFactory_4b440480::create() Test Failures
I want to try the ObjectManager in Magento\TestFramework\ObjectManager not the one in magento/framework/TestFramework/Unit/Helper/ObjectManager
Here is my code:
before class definition:
use Magento\TestFramework\ObjectManager;
after class definition:
public function testTheModuleIsConfiguredAndEnabled()
{
/** @var ObjectManager $objectManager */
$objectManager = ObjectManager::getInstance();
$moduleList = $objectManager->create(ModuleList::class);
$this->assertTrue($moduleList->has($this->moduleName));
}
Here is the error message:
PHP Fatal error: Class 'Magento\TestFramework\ObjectManager' not found
Best Answer
For unit tests you should use
Magento\Framework\TestFramework\Unit\Helper\ObjectManager
which allows to create any object with needed arguments (if they aren't passed, mocks will be created instead).The
Magento\TestFramework\ObjectManager
is used only by integration tests and you get thePHP Fatal error: Class 'Magento\TestFramework\ObjectManager' not found
error because the differentautoload.php
file should be used.For more details, please, see the testing section from official the Magento 2 dev docs.