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:
1 2 3 |
Find: (.*) (.*),\n Replace: /**\n* $1\n*/\nprotected $2Mock;\n\n |
Example text input:
1 2 3 |
\Magento\Checkout\Model\Session $checkoutSession, \Magento\Shipping\Model\Rate\ResultFactory $rateResultFactory, |
Output:
1 2 3 4 5 6 7 8 9 10 |
/** * \Magento\Checkout\Model\Session */ protected $checkoutSessionMock; /** * \Magento\Shipping\Model\Rate\ResultFactory */ protected $rateResultFactoryMock; |
Create Mock Objects
Regex:
1 2 3 |
Find: (.*) \$(.*),\n Replace: \$this->$2Mock = \$this->getMockBuilder($1::class)->disableOriginalConstructor()->getMock();\n |
Example text input:
1 2 3 |
\Magento\Checkout\Model\Session $checkoutSession, \Magento\Shipping\Model\Rate\ResultFactory $rateResultFactory, |
Output:
1 2 3 4 5 6 7 8 9 10 |
$this->checkoutSessionMock = $this ->getMockBuilder(\Magento\Checkout\Model\Session::class) ->disableOriginalConstructor() ->getMock(); $this->rateResultFactoryMock = $this ->getMockBuilder(\Magento\Shipping\Model\Rate\ResultFactory::class) ->disableOriginalConstructor() ->getMock(); |
How would you rate this article?
★ ★ ★ ★ ★