Zend Framework/PHPUnit: How to Stub/Mock an object method that connects to a database?

Posted by Andrew on Stack Overflow See other posts from Stack Overflow or by Andrew
Published on 2010-06-17T16:17:42Z Indexed on 2010/06/17 16:23 UTC
Read the original article Hit count: 213

Filed under:
|
|
|

In my Zend Framework project, I have a form that I am testing. In my form, a multi-select element gets its options from a model, which gets the data from the database.

public function init()
{
    $this->addElement('select', 'Region_ID', array('multiOptions' => $this->getRegions()));
}

protected function getRegions()
{
    $mapper = new Model_RegionMapper();
    return $mapper->getFormSelectData(); //this method will try to connect to a database (or get another object that will connect to the database)
}

I tried copying the example in the PHPUnit documentation, but it doesn't seem to be working.

public function setUp()
{
    $stub = $this->getMock('Model_RegionMapper');
    $stub->expects($this->any())
        ->method('getFormSelectData')
        ->will($this->returnValue(array('testdata')));
}

public function testFoo()
{
    //this will fail
    $form = new My_Form();
}

The test fails because it is trying to find a table in the database that doesn't exist. But I don't want it to connect to the database at all. How do I correctly stub/mock this method so that it doesn't call the database?

© Stack Overflow or respective owner

Related posts about zend-framework

Related posts about phpunit