Write Unit Tests For Your WordPress Plugin Using PhpStorm Code Completion

Git clone the WordPress develop repository somewhere on your hard drive:

git clone git@github.com:WordPress/wordpress-develop.git

Open wordpress-develop/tests/phpunit/includes/phpunit6-compat.php in a text editor.

PHPUnit version 5: Comment out the class_alias() functions in phpunit6-compat.php because these break PhpStorm code completion. (These files aren’t actually used by the testing framework, we only downloaded them so they could be included in the Project Configuration’s Include Path.)

PHPUnit version 6 and up: Do the same thing as PHPUnit 5, the paragraph above, except leave this line uncommented:

class_alias( 'PHPUnitFrameworkTestCase', 'PHPUnit_Framework_TestCase' );

In PhpStorm, go to: Settings -> Languages & Frameworks -> PHP and add wordpress-develop/tests/phpunit/includes to your Include Path.

Use WP-CLI to generate the tests scaffolding.

Write tests that extend WP_UnitTestCase. Look at the code in wordpress-develop/tests/phpunit/tests for examples.


4 thoughts on “Write Unit Tests For Your WordPress Plugin Using PhpStorm Code Completion”

  1. Such a simple solution that I never thought of before. Thanks for the post! It’ll be nice not needing to do a google search for the (rather sparse) WP unit testing documentation.

  2. This is an excellent tip but I’m still not seeing methods like assertEquals() available. Am I missing something? I see see WP specific functions available.

    1. Add PHPUnit to your list of known libraries.

      For me, because I installed it with Composer, assertEquals() leads to vendor/phpunit/phpunit/src/Framework/Assert.php

      If you can’t do that, git clone PHPUnit from GitHub and add it to your Include Path like you did the WordPress tests.

  3. Changing
    `abstract class WP_UnitTestCase_Base extends PHPUnit_Framework_TestCase {`
    `abstract class WP_UnitTestCase_Base extends PHPUnit\Framework\TestCase {`

    seems to do the trick too.

Leave a Reply

Your email address will not be published. Required fields are marked *