获取模拟方法调用的参数


PHPUnit: get arguments to a mock method call

我目前正在处理一个存储敏感数据的项目,因此必须能够根据请求删除它们。

我想测试我的实体(patient)是否以空电话号码保存到数据库中。首先要做的是:获取传递给PatientDao::savePatient(PatientModel $patient)的参数,并查看其phoneNumber属性。

下面是PatientDao接口:

interface PatientDao {
    function savePatient(PatientModel $patient);
}

和测试文件中的代码:

$this->patientDao                    // This is my mock
            ->expects($this->once()) 
            ->method('savePatient'); // savePatient() must be called once
$this->controller->handleMessage(...);
$patient = ??; // How can I get the patient to make assertions with it ?

我怎样才能做到这一点,或者是否有其他方法可以确保用空电话号码保存患者?

您可以使用returnCallback()对参数进行断言。记住通过PHPUnit_Framework_Assert静态地调用assert函数,因为你不能在闭包中使用self

$this->patientDao
        ->expects($this->once()) 
        ->method('savePatient')
        ->will($this->returnCallback(function($patient) {
            PHPUnit_Framework_Assert::assertNull($patient->getPhoneNumber());
        }));

这是我使用的技巧。我将这个私有方法添加到我的测试类中:

private function captureArg( &$arg ) {
    return $this->callback( function( $argToMock ) use ( &$arg ) {
        $arg = $argToMock;
        return true;
    } );
}

设置mock时:

$mock->expects( $this->once() )
    ->method( 'someMethod' )
    ->with( $this->captureArg( $arg ) );

之后,$arg包含传递给mock的参数的值。

让Mock objects方法返回第一个参数:

$this->patientDao                    // This is my mock
            ->expects($this->once()) 
            ->method('savePatient') // savePatient() must be called once
            ->with($this->returnArgument(0));

你可以断言它是NULL

有一件事-在闭包中你仍然可以访问$this,在这种情况下它会给你:

$this->patientDao
    ->expects($this->once()) 
    ->method('savePatient')
    ->will($this->returnCallback(function($patient) {
        $this->assertNull($patient->getPhoneNumber());
    }));