The object manager is not the correct way to do this. Use dependency injection via the constructor whenever possible.
You are getting that error because your controller extends another class, but you are not following the parent class's constructor, or you did not clear the cache.
You have not provided your code, but I assume your controller extends \Magento\Framework\App\Action\Action
. If you open that, you'll see the constructor signature for that class is:
/**
* @param \Magento\Framework\App\Action\Context $context
*/
public function __construct(
\Magento\Framework\App\Action\Context $context
) {
// ...
}
You're getting the error because Magento is trying to inject a Context object, and you're asking for a Customer. To inject your model, your class constructor needs to look like this:
protected $customer;
/**
* @param \Magento\Framework\App\Action\Context $context
* @param \Demo\HelloWorld\Model\Customer $customer
*/
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Demo\HelloWorld\Model\Customer $customer
) {
$this->customer = $customer;
parent::__construct($context);
}
Make that change, then flush the Magento cache (or folder var/cache), and then it should work.
Note: This is assuming your Customer class is injectable. If it's loaded from the database, you need to inject CustomerFactory instead, and then call $customer = $this->customerFactory->create()
.
First of all better to do not mock class under test.
Second one, better to use plugins instead of class overwrite.
And last, you must pass all parameters of parent constructor to your class.
Simplest way to instantiate class is using objectMangerHelper
$objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this);
$this->collection = $objectManager->getObject(
'SR\RewriteSales\Model\Resource\Order\Collection',
[
'resource' => $resource,
'connection' => $connection,
]
);
Best Answer
You can get by following code.
Below is code for your logic
This code is given here in answer.