This question came to mind after I've seen the edits made by Vinai to my answer here.
Let's say we have a class to test with a constructor like this
namespace Some\Namespace;
class SomeClass
{
public function __construct(
\Product $product,
\Category $category
) {
$this->product = $product;
$this->category = $category;
}
}
I've seen in the core Magento 2 unit tests this way to mock it:
$objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this);
$productMock = $this->getMockBuilder('Product')
->disableOriginalConstructor()
->getMock();
$categoryMock = $this->getMockBuilder('Category')
->disableOriginalConstructor()
->getMock();
$model = $objectManager->getObject(
'Some\Namespace\SomeClass',
[
'product' => $product,
'category' => $category
]
);
And this works. I've used similar approaches in my own tests.
But Vinai made an edit (and I trust that this edit works).
This
$this->getMockBuilder('Product')
Became this
$this->getMockBuilder(\Product::class).
What's the difference? (I know what ::class
means and does so don't explain this).
Then this:
$model = $objectManager->getObject(
'Some\Namespace\SomeClass',
[
'product' => $product,
'category' => $category
]
);
became this:
$model = new \Some\Namespace\SomeClass($product, $category);
When should I use the object manager helper to instantiate classes and when should I just use new
? Or why should I use one instead of the other?
coding-standards
. – Marius♦ Jun 23 '16 at 10:23