Magento 2 – ObjectManager Unusable in Unit Tests

magento2phpunittesting

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:

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 the PHP Fatal error: Class 'Magento\TestFramework\ObjectManager' not found error because the different autoload.php file should be used.

For more details, please, see the testing section from official the Magento 2 dev docs.