Run PHPUnit-tests in Drupal 7

Roman Zimmermann's picture
Roman Zimmermann

Why am I using PHPUnit instead of Drupal's own Simpletest module?

While developing I like to continually write Unit-Tests for my module as I go. For that I need a fast way to execute those tests - so it is not possible to do a full DB-bootstrap (or even a reload of a cached DB-script) after every test. Instead I try to really build unit-tests that don't modify the database.  Therefore I need to make heavy use of Mock- & Stub-Objects. PHPUnit provides a nice API for building the objects - Drupal's simpletest doesn't.

Set-up your test environment

To execute those scripts you need to checkout my gist-repository. To execute Unit-Tests in the command-line simply go to a Drupal site (ie. /var/www/drupal/sites/default) and use dphpunit.bash just as you would use the phpunit command.

How does it work?

The script consists of 3 files:

  • dphpunit.bash - which simply invokes drun-dphpunit.php with a few extra parameters. It's needed because PHP is incapable of dealing with symlinks correctly.
  • drun-dphpunit.php - which is basically the same as the upstream phpunit runner, except that it handles the extra parameter
  • - which makes a Drupal bootstrap very similar to drush

Any questions?

Feel free to drop me a comment …



I cloned your gist repo and tried it locally on a ubuntu box. I got PHPUnit installed(v 3.6). After finished the cloning, the first issue I got was that when I issue the command


I got the error that said unrecognized interpreter because the first line contains a special character, it was like #!/bin/bash^M so I converted the file from DOS to Unix format in emacs and that issues seemed gone after that.

Then I got the error saying PHP_CodeCoverage_Filter::getInstance() is undefined, so I installed PHP_CodeCoverage with pear and the filter class seems to be there, but seems I'm getting the new version and there is no method called getInstance(), but anyway I commented the lines trying to do code coverage stuff and re issued the command, the error was gone, but it didn't have any output.

I'm still not sure how to use this library at this point, I hope maybe you could help me understand the internals and the essential parts to get PHPUnit get successfully bootstrapped. I did looked your code and drush's implementation but haven't figured it out yet.

I also looked this post but it was written against drupal 6 and I confirmed with the author that it doesn't work in D7. So your posting seems to be the only clue I got now on this topic.


Roman Zimmermann's picture

After taking a closer look at your problem description and my scripts I'm pretty sure that your phpunit setup is not functional at this point. Does it work when you try to run unit tests with PHPUnit's own executable?