PHPUnit and namespaces


Just some quick notes about unexpected interactions I found when unit testing namespaced PHP code with PHPUnit.

Escape your namespace separators

In general, you need to double all of your namespace separators (i.e. escape the backslash with another backslash), like so:

phpunit --skeleton-test KuCal\\Api Api.php

This is the correct usage. However, the following the form (currently) in the docs:

phpunit --skeleton-test KuCal\Api Api.php

I've submitted the above as a documentation issue so it may be fixed by the time anybody reads this. Moving on.

Remove leading separators for getMock

You may also have to remove leading slashes from namespaced classes in getMock.

This is how the class is called in my PHP, just wrapped in single quotes. It fails.


This is the call with the namespace separators escaped, as above. It also fails:


This is the code with escaped separators and the first root separator removed. This version succeeds:



As a final note, the 2nd point above doesn't seem to apply to the @expectedException annotation. I haven't tried it with other annotations, but this is still perfectly valid and effective:

 * @expectedException \InvalidArgumentException


Several questions on StackOverflow, and the PHPUnit docs.

Tags: php, phpunit