2008年10月1日星期三

[fw-mvc] How to test action controller method that communicates with external resources.

Hello!

My controller action method uses $this->_getWebServiceCommunication()
to obtain object to communicate with remote web service.
This object itself is well tested, but I dunno how can I test
controller method that makes use of this object.
I can mock controller action $this->_getWebServiceCommunication() to
return fake object for testing purposes, but how can I make this
controller object to be used during
Zend_Test_PHPUnit_ControllerTestCase::dispatch() ?

Sample code below:

<?php

class IndexController extends Zend_Controller_Action
{

// How can I test this method without connecting to external webservice
public function indexAction()
{
// ...
$this->_getWebServiceCommunication()->sendRequest(123);
// ...
}

private function _getWebServiceCommunication()
{
return new Custom_WebServiceCommunication();
}


Cheers,
Piotr Czachur

1 条评论:

WaaX 说...

-Create a stub objet that extend your controller, something like
class TestIndexController extends IndexController

-Mark the private method
_getWebServiceCommunication as protected

-Overwrite _getWebServiceCommunication so it return an object that fake communication. For this you can create another stub object that extend your normal service except it returns predefined response that you can from your test.