我正在开发一个允许用户通过短信进行互动的项目。我已经将Zend Framework的请求和响应对象子类化,以从SMS API获取请求,然后发回响应。当我通过开发环境“测试”它时,它可以工作,但我真的很喜欢进行单元测试。
但是在测试用例类中,它没有使用我的请求对象,而是使用Zend_Controller_Request_HttpTestCase。我很确定我对响应对象有同样的问题,我现在还没有。
我的简化测试课程:
class Sms_IndexControllerTest extends Zend_Test_PHPUnit_ControllerTestCase {
...
public function testHelpMessage() {
// will output "Zend_Controller_Request_HttpTestCase"
print get_class($this->getRequest());
...
}
}
如果我在运行测试之前覆盖请求和响应对象:
public function setUp()
{
$this->bootstrap = new Zend_Application(APPLICATION_ENV,
APPLICATION_PATH . '/configs/application.ini');
parent::setUp();
$this->_request = new Sms_Model_Request();
$this->_response = new Sms_Model_Response();
}
在调用前端控制器进行调度之前,我无法使用Zend_Controller_Request_HttpTestCase中的方法(如setMethod和setRawBody)来设置我的测试。
在将子请求和响应对象子类化后,如何对控制器进行单元测试?
答案 0 :(得分:0)
您可以尝试在Sms_IndexControllerTest中定义getRequest和getResponse方法,例如:
public function getRequest()
{
if (null === $this->_request) {
$this->_request = new Sms_Model_Request;
}
return $this->_request;
}
public function getResponse()
{
if (null === $this->_response) {
$this->_response = new Sms_Model_Response;
}
return $this->_response;
}
答案 1 :(得分:0)
我最终做的是将Request和Response测试用例对象的整个代码复制到我自己的请求和响应类的子类化版本中。这是请求对象的要点:
转发Request和Response对象并粘贴RequestTestCase的整个代码:
class MyApp_Controller_Request_SmsifiedTestCase
extends MyApp_Controller_Request_Smsified {
// pasted code content of RequestTestCase
}
然后在ControllerTest的setUp()函数中设置它们:
class Sms_IndexControllerTest extends Zend_Test_PHPUnit_ControllerTestCase {
{
...
public function setUp()
{
$this->bootstrap =
new Zend_Application(APPLICATION_ENV, APPLICATION_PATH
. '/configs/application.ini');
parent::setUp();
$this->_request =
new MyApp_Controller_Request_SmsifiedTestCase();
$this->_response =
new MyApp_Controller_Response_SmsifiedTestCase();
}
...
}
然后它奏效了。