Skip to content

Instantly share code, notes, and snippets.

@kanduvisla
Last active October 24, 2016 11:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kanduvisla/6f118913a9ed9319876ddaef362125f6 to your computer and use it in GitHub Desktop.
Save kanduvisla/6f118913a9ed9319876ddaef362125f6 to your computer and use it in GitHub Desktop.
Regex to replace class signature to mock properties

Regexes for quickly mocking stuff

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* @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;

Create Mock Objects

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();

Populate setConstructorArgs()

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,
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment