1

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

1 Answer 1

4

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 a create() method. As explained in the linked answer, you need getObject():

public function getObject($className, array $arguments = [])

I am using the ObjectManager::create method to get an Instance of my Helper class in another custom class. So i shouldnt use ~::create at all?

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 manager Magento\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.

3
  • I am using the ObjectManager::create method to get an Instance of my Helper class in another custom class. So i shouldnt use ~::create at all? Mar 4, 2016 at 12:37
  • see updated answer Mar 4, 2016 at 13:00
  • Thank you for pointing out that using the objectManager there is totally wrong, even if it works :) Mar 6, 2016 at 12:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.