I am trying to write UnitTests for my module for magento 2.
For this purpose i need access to the objectManager->create method.
i already tried what Marius suggested here: How to obtain the Object Manager in Unit-Tests?
but if i run those unittest, i get the following error message:
PHP Fatal error: Call to undefined method Magento\Framework\TestFramework\Unit\Helper\ObjectManager::create()
am I doing anything wrong?
I searched through the magento core code, but I wasn't able to get the "real" objectManager
Best Answer
The object manager for unit tests is in
magento/framework/TestFramework/Unit/Helper/ObjectManager.php
and you obviously instantiated it, otherwise you would not get this error message. But you are using it wrong, it does not have acreate()
method. As explained in the linked answer, you needgetObject()
:Not with this object manager helper for unit tests. It has a different interface than the regular object manager. It sounds like you are passing the unit test object manager to a class under test. This is not how it is intended to be used.
In an integration test you can use:
Magento\TestFramework\ObjectManager::getInstance()
which works like the "real" object manager. In a unit test, you could instantiate or mock the real object managerMagento\Framework\App\ObjectManager
.But the fact that you need it, tells you that there's something wrong. Don't use the object manager to get an instance of your helper. Instead, add your helper as a constructor parameter and let Magento handle the Dependency Injection.