How to prevent PhpStorm from showing an Expected... warning when using PHPUnit mocks?
I found a workaround to this problem in the Jetbrain blog at PhpStorm Type Inference and Mocking Frameworks. The important part:
By default, PhpStorm is capable of figuring out the available methods on the mock object. However, it only displays those for PHPUnit’s PHPUnit_Framework_MockObject_MockObject class. Fortunately, we can solve this by instructing PhpStorm to infer type information from other classes as well, by using a simple docblock comment.
So to make the warning disappear, we need to add /** @var InterfaceA */
/** @var InterfaceA|PHPUnit_Framework_MockObject_MockObject */
(cudos to Supericy) to let PhpStorm know our mock actually implements InterfaceA
:
interface InterfaceA{
}
class ClassA{
public function foo(InterfaceA $foo){}
}
class PhpStormTest extends PHPUnit_Framework_TestCase
{
public function testFoo(){
/** @var InterfaceA|PHPUnit_Framework_MockObject_MockObject */
$mock = $this->getMock("InterfaceA");
$a = new ClassA();
$a->foo($mock);
}
}
This bugged me for some time, hope it helps someone :)
Edit
Since PHPUnit_Framework_MockObject_MockObject
is really ugly to type, you can abbreviate it via MOOMOO
and let PHPStorms auto-complete do the rest: