Traits for PHPUnit Testcases

project-stage-badge license-badge

Traits that offer helper functions to be used in PHPUnit TestCases.


This projects contains various traits that offer convenience methods for tasks that occur when creating test code.


composer require 'potherca/phpunit-testcase-traits'


Add a use statement for a desired trait to a class definition. The public API of that trait can then be used in the defined class.

For full details on how to use traits, please refer to the section on traits in the PHP manual.

PHP 5.3 compatibility

Traits were not introduced until PHP5.4 so for older versions (i.e. PHP5.3) another way to load the trait’s functionality is needed. A traitShim function is provided that can be used from a magic __call method.

This is done by adding the following code to each (abstract base) test-case were a Trait is to be used(1):

class ExampleTest extends \PHPUnit_Framework_TestCase
    // ....

    final public function __call($name, array $parameters)
        return \Potherca\PhpUnit\Shim\Util::traitShim($this, $name, $parameters);

    // ....

The public API of all traits can then be used.

In order to aid text-editors and IDEs in offering auto-completion, the following doc-block can be added to the test-case class:

 * @method array[] createDataProvider(array $subject)
 * @method \PHPUnit_Framework_MockObject_MockObject | \PHPUnit\Framework\MockObject\MockObject createObjectFromAbstractClass($className)
 * @method string getCompatibleExceptionName($exceptionName)
 * @method void setDataProviderMaximumKeyLength($length)
 * @method void setDataProviderSortByKey($sort)
 * @method void setNonPublicProperty($subject, $name, $value)

(1) Alternatively, the src/Shim/function.traitShim.php could be loaded using composer’s autoloader.

Available traits

Functioning usage examples are available in the example directory. All examples can be run with phpunit. Simply use the --config flag to point to the desired config file (either example-php-phpunit.xml for the traits or example-php53-phpunit.xml for the PHP5.3 compatible Trait shims).