Isolating PHPUnit tests to run

Authored by

PHPUnit tests can be really slow, especially for large plugins that integrate with external APIs. It can be tempting thus to bypass the pre-commit hook via git commit --no-verify, but then Travis CI (or Bamboo) will eventually complain and the issue will come back to you, or worse the issue will get ignored. So we should always be running unit tests before we push up our code for review and merging.

Since we generally break up our unit tests in a way where each unit test file corresponds to a functional class file, you can easily load just the one test PHP file instead of running everything. So in a plugin, if you made a change to php/class-collection-widget.php then you can just run the tests on the corresponding test file via:

phpunit tests/test-class-collection-widget.php

You can also limit tests to just individual test methods by using --filter:

phpunit --filter test_flush_caches_related_to_post tests/test-class-collection-widget.php

If that test method is unique across all the test files, you can omit the explicit test file:

phpunit --filter test_flush_caches_related_to_post

Another way to isolate tests to run is to add groups to your tests:

<?php 
class ClassCollectionWidgetTest extends Test_Case { 

    /**
     * @group ABC-123 
     * @see Collection_Widget::can_use_esi() 
     */ 
    function test_can_use_esi() { 
        $this->assertFalse( $this->collection_widget->can_use_esi( 1 * \MINUTE_IN_SECONDS ) );
        /* ... */
    }
/* ... */

You can then just tell PHPUnit to run the test methods for the ticket ABC-123 via:

phpunit --group ABC-123

You can add multiple groups to a single method.

For more information on @group, see the docs.

All of this can greatly speed up your work with PHPUnit tests, and you can feel less guilty for using --no-verify 🙂

One thought on “Isolating PHPUnit tests to run”

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.