Features Releases

Working With PHPUnit and PhpStorm

Community stalwart and Laravel aficionado Adam Wathan blogged on his PHPUnit workflow in Sublime text. I was sent a Tweet asking how you do this in PhpStorm:


Here’s the answer.

First, Adam talks about having templates you can use to generate the boilerplate code around your test quickly. PhpStorm already does this when you create a unit test, either from the “Navigate to Tests” action or if you use “New” in the project manager and select PHPUnit then PHPUnit Test.


You can edit these templates by going to the settings pane and looking under EditorFile and Code Templates and then PHPUnit Tests. The templates have some predefined variables you can use to tailor the new file exactly to your liking.


You can learn more in the Updating Your Templates in PhpStorm blog post.

Next, Adam shows us how he has used snippets when he wants to create a new test to reduce the typing of the function definitions and annotation. We can do exactly the same in PhpStorm using Live Templates.

Live templates allow you to type some characters and then use the Tab key to substitute the key for a snippet of code. PhpStorm already comes with a batch of them out of the box – try typing `rqr` and then pressing Tab in a PHP file to see the results. We can use Live Templates to reproduce Adam’s Sublime Text snippet. Live Templates can be found under Editor then Live Templates in the Settings, and you’ll want to create this under the PHP scope.


Now, when we type the abbreviation `test` into our Test class, and press Tab, we get the function definition with annotation, with the cursor in the right place to type our test name.


Finally, Adam talks about how to run just the tests in a single file, a single class, or a single method. This is relatively easy in PhpStorm if you’re using the PhpStorm test runner already.

To run all the tests in a single file, right-click the test in the Project Pane (the left-hand navigation pane), and select Run <Filename>.

To run all the tests in a single class, right-click the class name in the editor, and select Run <Class Name>.

To run the tests in a single method, right-click the method name, and select Run <Method Name>.


I hope that covers everything. A big thank you to Adam Wathan for all he does to promote testing in the Laravel and wider PHP communities!

 — Gary and the PhpStorm Team


image description