2011-10-19 63 views
11

我目前正在開發一個存儲敏感數據的項目,因此必須能夠根據請求擦除它們。PHPUnit:將參數傳遞給模擬方法調用

我想測試我的實體(患者)是否保存到數據庫與一個空電話號碼。第一個想法是:將參數傳遞給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 ? 

我如何能做到這一點,或有任何其他的方式,以確保病人用一個空電話號碼保存?

回答

23

您可以使用returnCallback()對參數進行斷言。請記住通過PHPUnit_Framework_Assert靜態調用斷言函數,因爲您不能在閉包中使用self

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

這應該做的伎倆,許多thx! – aspyct

+1

在這裏工作過。注意:如果參數需要多個參數,則即使您不想全部測試,也需要全部包含它們。例如'$ this-> returnCallback(function($ patient,$ someOtherParameter){})'。 – fazy

4

充分利用Mock對象方法返回的第一個參數:

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

然後可以斷言它是NULL

+0

我從來沒有在「with」中使用$ this-> return * ......看起來很有趣!但是如何在測試函數中稍後獲得該值本身,它是如何返回給我的? – aspyct

+0

你是用模擬來做內省嗎? – hakre

+0

我不這麼認爲......我猜不。 – aspyct

5

這是我使用的技巧。當設置了模擬然後

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

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

之後,$arg包含傳遞給模擬參數的值,我加了這個私有方法,我的測試類。