How to Obtain the Object Manager in Unit Tests

magento2object-managerunit tests

I've created the second unit-test for my second class. The second class will take a dependency of a first class instance and in one test I'd like to use the object manager to create the second class.

How do I manage that my unit-test gets the object manager injected in Magento 2 so that I can use it?

Best Answer

You can use in your unit test an instance of \Magento\Framework\TestFramework\Unit\Helper\ObjectManager.

/**
 * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager
 */
protected $objectManager;
public function setUp()
{
    parent::setUp();
    ....//your mocks go here
    $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this);
}

Then you can use this object manager to instantiate your other class:

$this->objectManager->getObject('Your\Other\Class\Here');