如何使用phpUnit对我的子类zend框架请求和响应对象进行单元测试


How to unit test my subclassed zend framework request and response objects with phpUnit

我正在做一个项目,该项目允许用户通过短信进行交互。我已经将ZendFramework的请求和响应对象进行了子类化,以便从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)来设置测试。

在对请求和响应对象进行子类化之后,如何对控制器进行单元测试?

您可以尝试在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;
}

我最终所做的是将请求和响应测试用例对象的整个代码复制到我自己的请求和响应类的子类版本中。以下是请求对象的要点:

对请求和响应对象进行子分类,并粘贴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();
        }
        ...
     }

然后它起作用了。