PHPUnit for Drupal: A very basic how-to.

How to use this example module

You really should be reading the various docblocks in the test files.

How To:

  • PHPUnit tests belong in their own directory, so they won't be loaded by the autoloader during normal bootstrap. This means you should have a /tests/src directory in the root of your module directory.

  • Your tests should be in the Drupal\Tests\[your_module]\Unit namespace. Under Drupal's PSR-4 system, this means your PHPUnit-based tests should go in a [your_module]/tests/src/Unit directory.

  • Your test case should subclass Drupal\Tests\UnitTestCase.

  • You can run PHPUnit-based tests from within Drupal 8 by enabling the Testing module and then selecting the PHPUnit group from the testing page. As of this writing, this method doesn't provide any useful output.

Standard PHPUnit Practices

You can (and really, should) run PHPUnit from the command line.

On unix-based systems this means you need to cd core and then

./vendor/bin/phpunit

On Windows-based systems, assuming you have php in your path,

php ./vendor/phpunit/phpunit/composer/bin/phpunit --group phpunit_example

Also, you should mark your tests as belonging to a group, so they can be run independently. You do this by annotating your test classes with @group group_name. You should have a @group for your module name, and you should also have a @group for integrations, such as views.

So, for instance, to run all of the PHPUnit example tests, you would type

./vendor/bin/phpunit --group phpunit_example

As you can see, including a @group annotation is a good idea.