This is a small collection of regular expressions to find pieces of code and replace them with PHPUnit mocks. It's useful for copy/pasting existing pieces of code (a constructor signature for example) and transforming them into usefull code for mocking in PHPUnit, without having to type everything out.
Disclaimer: some small code formatting might be required afterwards, but hey it's better than nothing ...
Regex:
Find: (.*) (.*),\n
Replace: /**\n* @var $1|\\PHPUnit_Framework_MockObject_MockObject\n*/\nprotected $2Mock;\n\n
Example text input:
\Magento\Checkout\Model\Session $checkoutSession,
\Magento\Shipping\Model\Rate\ResultFactory $rateResultFactory,
Output:
/**
* @var \Magento\Checkout\Model\Session|\PHPUnit_Framework_MockObject_MockObject
*/
protected $checkoutSessionMock;
/**
* @var \Magento\Shipping\Model\Rate\ResultFactory|\PHPUnit_Framework_MockObject_MockObject
*/
protected $rateResultFactoryMock;
Regex:
Find: (.*) \$(.*),\n
Replace: \$this->$2Mock = \$this\n\t->getMockBuilder($1::class)\n\t->disableOriginalConstructor()\n\t->getMock();\n\n
Example text input:
\Magento\Checkout\Model\Session $checkoutSession,
\Magento\Shipping\Model\Rate\ResultFactory $rateResultFactory,
Output:
$this->checkoutSessionMock = $this
->getMockBuilder(\Magento\Checkout\Model\Session::class)
->disableOriginalConstructor()
->getMock();
$this->rateResultFactoryMock = $this
->getMockBuilder(\Magento\Shipping\Model\Rate\ResultFactory::class)
->disableOriginalConstructor()
->getMock();
Regex:
find: (.*) \$(.*),\n
replace: \$this->$2Mock,\n
Example text input:
\Magento\Checkout\Model\Session $checkoutSession,
\Magento\Shipping\Model\Rate\ResultFactory $rateResultFactory,
Output
$this->checkoutSessionMock,
$this->rateResultFactoryMock,