为PHPUnit的模拟对象定义类型

Ali*_*Ali 4 php phpunit phpdoc

我想知道是否可以使用phpdoc来定义特定范围内的某个对象(仅在方法内)作为PHPUni的Mock,所以在该方法中我可以利用类型提示,例如 - > expected, - > methods等等就像你刚刚创建模拟而不将其解析为真正的类一样.

这是一个示范:

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->....
    }
}
Run Code Online (Sandbox Code Playgroud)

Ale*_*ons 7

/**
 * @var SomeClass|\PHPUnit_Framework_MockObject_MockObject
 */
private $someMock;
Run Code Online (Sandbox Code Playgroud)

你可以用方法做同样的事情:

/**
 * @return SomeClass|\PHPUnit_Framework_MockObject_MockObject
 */
private function getSomeMock()
{
    //....
}
Run Code Online (Sandbox Code Playgroud)

  • @Ali我认为这种语法仅在测试中有用.实际代码不应返回不同类的对象. (2认同)