credits: r.g-s A big regexp via photopin (license). posted on October 18th, 2016.

Regular Expressions for Quickly Mocking Stuff

He who controls the Regexp, controls the Universe

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 ...

Declare your parameters

Regex:

Find:       (.*) (.*),\n
Replace:    /**\n* $1\n*/\nprotected $2Mock;\n\n

Example text input:

\Magento\Checkout\Model\Session $checkoutSession,
\Magento\Shipping\Model\Rate\ResultFactory $rateResultFactory,

Output:

/**
 * \Magento\Checkout\Model\Session
 */
protected $checkoutSessionMock;

/**
 * \Magento\Shipping\Model\Rate\ResultFactory
 */
protected $rateResultFactoryMock;

Create Mock Objects

Regex:

Find:       (.*) \$(.*),\n
Replace:    \$this->$2Mock = \$this->getMockBuilder($1::class)->disableOriginalConstructor()->getMock();\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();

Phpstorm Regexp