PhpStorm Type Inference and Mocking Frameworks
Recently, we received a question on Twitter asking about how PhpStorm handles type inference when working with mocking frameworks. Imagine having the following two classes:
When writing a unit test for ClassA, it’s very easy to mock ClassB using PHPUnit’s mocking capabilities. By mocking ClassB, you can mold an instance of ClassB and add additional validations on it without having to modify the code for ClassB. For example, you might want to validate that there’s only one call being made to ClassB’s bar() method.
PhpStorm gives you code completion on PHPUnit so it’s really easy to setup a mock object for ClassB:
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. Adding such comment can be done using PhpStorm’s “Add PHPDoc comment” intention (ALT+Enter on the variable):
If we only want to have type information for ClassB, we should use:
To have type information for multiple classes, ClassB and PHPUnit’s mock object, we can use:
A little trick that makes your development a lot easier. Enjoy!
Develop with pleasure!
– JetBrains Web IDE Team