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

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.

  • 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? – Sebastian L Mar 4 '16 at 12:37
  • see updated answer – Fabian Schmengler Mar 4 '16 at 13:00
  • Thank you for pointing out that using the objectManager there is totally wrong, even if it works :) – Sebastian L Mar 6 '16 at 12:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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