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

About Maarten Balliauw

Maarten Balliauw is a Developer Advocate at JetBrains, working on .NET tools and Space. He focuses on .NET, Azure, web technologies and application performance. Maarten is a frequent speaker at various national and international events. In his free time, he brews his own beer. Follow him on Twitter or check out his personal blog.
This entry was posted in Cool Feature, PhpStorm, Tutorial and tagged , , , , . Bookmark the permalink.