Define type for PHPUnit's mock objects

1.7k views Asked by At

I was wondering if its possible to use phpdoc to define some object in specific scope (inside a method only) as PHPUni's Mock, so in that method i can take advantage of type-hints, such as ->expected, ->methods and so on, just like when you just create the mock without addressing it to its real class.

here is an demonstration:

class someTest extends PHPUnit
{
    // here, usually we define the real class (SomeClass in this example)
    /** @var SomeClass */
    private $someMock;

    public function setUp()
    {
        $this->someMock = $this->getMock(SomeClass::class);
    }

    public function testSomethingInSomeClass()
    {
        // here i expect the type hint i defined in the beginning of this test class and its fine
        $a = $this->someMock->someMethodFromSomeClass();
    }

    private function setSomeMethodOnMock()
    {
        // but here i would like to have the type-hint for phpunit's mock object
        // e.g. ->expects,  ->method() , ->willReturn() , etc.
        // if i don't define the mock alias the class type i get will be something like Mock_SomeClass_9873432
        $this->someMock->....
    }
}
1

There are 1 answers

4
Aleksander Wons On BEST ANSWER
/**
 * @var SomeClass|\PHPUnit_Framework_MockObject_MockObject
 */
private $someMock;

You can do the same thing with methods:

/**
 * @return SomeClass|\PHPUnit_Framework_MockObject_MockObject
 */
private function getSomeMock()
{
    //....
}