您好,欢迎访问一九零五行业门户网

phpunit解耦测试

各位好,目前在学习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
谢谢,非常有帮助
其它类似信息

推荐信息