各位好,目前在學習phpunit單元測試。
發現這個的一個問題沒辦法解決。
目前開發用的架構式 zend framework 1,對controller層測試的時候,被要求要把其中的model層解耦出來。
譬如:
public function phpunitAction(){ $enterpriseModel = new Model_Enterprise(); $sum = $enterpriseModel->getTotal(); print 'asd'; file_put_contents('xx.log',"suma is ".$sum[0]['total']."\r\n",FILE_APPEND); }
我寫測試案例的時候,需要在執行個體化的時候 不去資料庫裡查詢資料,而是使用phpunit 的mock對象去仿照一個對象。
我看了下文檔,自己寫了測試案例,但是好像有點問題。
public function testPhpunitAction(){ $oClientMock = $this->getMock('Model_Enterprise'); $res = array( 0=>array( 'total'=>22 ) ); $oClientMock->expects($this->once()) // 設定次數 ->method('getTotal') // 設定方法 ->will($this->returnValue($res)); // 設定方法傳回值 $enterpriseModel = new Model_Enterprise(); $sum = $enterpriseModel->getTotal(); $user_info['user_name'] = 'root'; $user_info['real_name'] = 'root'; $user_info['id'] = 1; $user_info['group_ids'] = array(0=>1); $session = new Zend_Session_Namespace('UserInfo'); $session->user_info = $user_info; $params = array('action' => 'phpunit', 'controller' => 'index', 'module' => 'analyze'); $url = $this->url($this->urlizeOptions($params)); $this->dispatch($url); }
但是這樣沒有作用。
跪求指點。
回複討論(解決方案)
1.$oClientMock 山寨 一個Model_Enterprise 對象
2. getMock第二個參數需要傳入需要山寨的方法 否則不山寨原方法
$oClientMock = $this->getMock('Model_Enterprise',array('getTotal')); $res = array( 0=>array( 'total'=>22 ) ); $oClientMock->expects($this->once()) // 設定次數 ->method('getTotal') // 設定方法 ->will($this->returnValue($res)); // 設定方法傳回值 $sum = $oClientMock->getTotal();
hi,你好,我是http://bbs.csdn.net/topics/390923963的樓主,諮詢過你一個phpunit的問題。
看了你的回複,對我很有協助。
我想諮詢的是,對於MVC的架構,怎麼對controller層進行解耦測試。
譬如我有一個 controller.
class EnterPrise_AnnounceController extends ZendX_Controller_Action
{
public function needchecknumAction() {
$announceModel = new Model_Announce();
$info = $announceModel->getTotal("status IN ('". Model_Announce::STATUS_PENDING ."')");
$info['result'] = $info['total'];
return Common_Protocols::generate_json_response($info);
}
}
怎麼在測試案例當中使用MOCK,在controller中不會去調用架構中的模型層,而是去調用我的mock呢?
hi,你好,我是http://bbs.csdn.net/topics/390923963的樓主,諮詢過你一個phpunit的問題。
看了你的回複,對我很有協助。
我想諮詢的是,對於MVC的架構,怎麼對controller層進行解耦測試。
譬如我有一個 controller.
class EnterPrise_AnnounceController extends ZendX_Controller_Action
{
public function needchecknumAction() {
$announceModel = new Model_Announce();
$info = $announceModel->getTotal("status IN ('". Model_Announce::STATUS_PENDING ."')");
$info['result'] = $info['total'];
return Common_Protocols::generate_json_response($info);
}
}
怎麼在測試案例當中使用MOCK,在controller中不會去調用架構中的模型層,而是去調用我的mock呢?
MOCK 不能類比類 只能類比對象 你要把controller中new的資料庫模型 換成 set/get的方式 set成一個mock
謝謝,非常有協助