phpstan / phpstan-phpunit

PHPUnit extensions and rules for PHPStan
MIT License
457 stars 45 forks source link
php php7 phpstan phpunit static-analysis static-code-analysis testing

PHPStan PHPUnit extensions and rules

Build Latest Stable Version License

This extension provides following features:

It also contains this strict framework-specific rules (can be enabled separately):

How to document mock objects in phpDocs?

If you need to configure the mock even after you assign it to a property or return it from a method, you should add PHPUnit_Framework_MockObject_MockObject to the phpDoc:

/**
 * @return Foo&PHPUnit_Framework_MockObject_MockObject
 */
private function createFooMock()
{
    return $this->createMock(Foo::class);
}

public function testSomething()
{
    $fooMock = $this->createFooMock();
    $fooMock->method('doFoo')->will($this->returnValue('test'));
    $fooMock->doFoo();
}

Please note that the correct syntax for intersection types is Foo&PHPUnit_Framework_MockObject_MockObject. Foo|PHPUnit_Framework_MockObject_MockObject is also supported, but only for ecosystem and legacy reasons.

If the mock is fully configured and only the methods of the mocked class are supposed to be called on the value, it's fine to typehint only the mocked class:

/** @var Foo */
private $foo;

protected function setUp()
{
    $fooMock = $this->createMock(Foo::class);
    $fooMock->method('doFoo')->will($this->returnValue('test'));
    $this->foo = $fooMock;
}

public function testSomething()
{
    $this->foo->doFoo();
    // $this->foo->method() and expects() can no longer be called
}

Installation

To use this extension, require it in Composer:

composer require --dev phpstan/phpstan-phpunit

If you also install phpstan/extension-installer then you're all set!

Manual installation If you don't want to use `phpstan/extension-installer`, include extension.neon in your project's PHPStan config: ``` includes: - vendor/phpstan/phpstan-phpunit/extension.neon ``` To perform framework-specific checks, include also this file: ``` - vendor/phpstan/phpstan-phpunit/rules.neon ```