为PHPUnit的模拟对象定义类型

时间:2015-06-11 09:47:27

标签: php phpunit phpdoc

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

这是一个演示:

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 个答案:

答案 0 :(得分:6)

<?php
$authenticateForRole = function ( $role = 'member' ) {
    return function () use ( $role ) {
        $user = User::fetchFromDatabaseSomehow();
        if ( $user->belongsToRole($role) === false ) {
            $app = \Slim\Slim::getInstance();
            $app->flash('error', 'Login required');
            $app->redirect('/login');
        }
    };
};
$app = new \Slim\Slim();
$app->get('/foo', $authenticateForRole('admin'), function () {
    //Display admin control panel
});

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

/**
 * @var SomeClass|\PHPUnit_Framework_MockObject_MockObject
 */
private $someMock;