potherca/phpunit-testcase-traits

This package is abandoned and no longer maintained. No replacement package was suggested.

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

v0.7.0 2018-01-25 13:34 UTC

README

project-stage-badge license-badge

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

Introduction

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

Installation

composer require 'potherca/phpunit-testcase-traits'

Usage

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

  • CreateDataProviderTrait -- Create data-provider arrays.
    Creates a key/value pair from a given one-dimensional array of values, which is meant to be returned from a data-provider method in a TestCase.

  • CreateObjectFromAbstractClassTrait -- Create an object instance from an abstract class.
    Creates a concrete object whose methods can be called and, thus, be tested.

  • GetCompatibleExceptionNameTrait -- Provide names of PHP5 compatible PHPUnit_Framework_Exception for (new) PHP7 Exceptions.

  • SetNonPublicPropertyTrait -- Change the value of a non-public class properties.

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).

Colophon