Skip to content

phpstan/phpstan-phpunit

Folders and files

NameName
Last commit message
Last commit date

Latest commit

4d0e94f · Nov 26, 2017

History

11 Commits
Nov 22, 2017
Oct 5, 2017
Oct 5, 2017
Oct 5, 2017
Oct 5, 2017
Oct 5, 2017
Oct 5, 2017
Nov 26, 2017
Oct 5, 2017
Nov 11, 2017
Oct 6, 2017
Oct 5, 2017
Nov 11, 2017
Oct 5, 2017

Repository files navigation

PHPStan PHPUnit extensions and rules

Build Status Latest Stable Version License

This extension provides following features:

  • createMock(), getMockForAbstractClass() and getMockFromWsdl() methods return an intersection type (see the detailed explanation of intersection types) of the mock object and the mocked class so that both methods from the mock object (like expects) and from the mocked class are available on the object.
  • getMock() called on MockBuilder is also supported.
  • Interprets Foo|PHPUnit_Framework_MockObject_MockObject in phpDoc so that it results in an intersection type instead of a union type.
  • Defines early terminating method calls for the PHPUnit\Framework\TestCase class to prevent undefined variable errors.

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

  • Check that both values passed to assertSame() method are of the same type.

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 = $foo;
}

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

Usage

To use this extension, require it in Composer:

composer require --dev phpstan/phpstan-phpunit

And 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