Error Identifier: phpunit.mockMethod
Every error reported by PHPStan has an error identifier. Here’s a list of all error identifiers. In PHPStan Pro you can see the error identifier next to each error and filter errors by their identifiers.
Code example #
<?php declare(strict_types = 1);
use PHPUnit\Framework\TestCase;
class UserService
{
public function getName(): string
{
return 'John';
}
}
class UserServiceTest extends TestCase
{
public function testUser(): void
{
$mock = $this->createMock(UserService::class);
$mock->method('getNamme')->willReturn('Jane');
}
}
Why is it reported? #
The method() call on a PHPUnit mock object references a method that does not exist on the mocked class. This is most likely a typo in the method name. In the example above, getNamme should be getName.
Since mock objects do not validate method names at compile time, this kind of mistake would only be caught at runtime when the test is executed. PHPStan detects it statically.
This rule is provided by the phpstan-phpunit extension.
How to fix it #
Correct the method name to match an existing method on the mocked class:
$mock = $this->createMock(UserService::class);
-$mock->method('getNamme')->willReturn('Jane');
+$mock->method('getName')->willReturn('Jane');
How to ignore this error #
You can use the identifier phpunit.mockMethod to ignore this error using a comment:
// @phpstan-ignore phpunit.mockMethod
codeThatProducesTheError();
You can also use only the identifier key to ignore all errors of the same type in your configuration file in the ignoreErrors parameter:
parameters:
ignoreErrors:
-
identifier: phpunit.mockMethod
Rules that report this error #
- PHPStan\Rules\PHPUnit\MockMethodCallRule [1] phpstan/phpstan-phpunit