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
Subscribe to Blog updates
Thanks, we've got you!
Laravel Best Practices: How to Automate Your Routine
5 useful tips to make your experience with the Laravel framework more productive
Qodana Clone Finder: Early Access Program
In December 2020, we announced the EAP for Qodana, which is rapidly evolving into a comprehensive platform that allows companies to perform multi-level evaluations of the quality of code they own, contract, or purchase. Qodana helps you detect bugs without relying on an IDE, either on a local machi…
How the Pest PhpStorm Plugin Will Improve Your Testing Workflow
Perhaps you’ve already heard of Pest. It is a new PHP testing framework with a focus on simplicity. The Pest PhpStorm plugin is a new addition to PhpStorm’s growing ecosystem. With this plugin, testing your code in your favorite IDE is even simpler and faster! The source code behind the plugin is…