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

This entry was posted in Cool Feature, PhpStorm, Tutorial and tagged , , , , . Bookmark the permalink.
  • Daniel Kullik

    Is there any difference between /** @var TYPE NAME */ and /** @var NAME TYPE */ for variables? Both seem to work in PhpStorm.


  • Tim Glabisch

    a bit bad is that you cant do thinks like /** @this ZEND_VIEW */

    is there a plan to extend the type inference? i would like to see something like:

    /** @returns `arguments[0].replace(‘_’, ‘/’)`
    function service_locator($…) { }

    this would be amazing for something like di’s

    • dex

      @Tim: Regarding first part of your comment… Do you want to get code assistance e.g. in your Zend view scripts? If so, it works well with /** @var $this Zend_View */ for me.

    • Andriy Bazanov

      Sounds like a bad idea to me. PHPDoc comments should really follow the standards and not re-inventing something completely different (like proposed example) for standard PHPDoc tags.

      In any case — I think this ticket is what you are after:

  • Maarten Balliauw

    @Daniel PhpStorm indeed supports both. The standard is /** @var TYPE NAME */ but a lot of libraries use the /** @var NAME TYPE */ syntax.

  • kris

    Just a little suggestion.

    I have seen that if I do CI and use phpdesigner then they can make me able to call auth->signin() through autocomplete phpstorm not have done it.

    biggest problem for me is Performance. I still not feel good even I have 8GB.

  • Richard Tuin

    This is a great feature. In which version of PHPStorm was this introduced?