views:

30

answers:

1

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?

+1  A: 

Mock the Model_RegionMapper.

  • Don't construct a Model_RegionMapper in your class, but pass it in instead.
  • When testing, pass in a fake Model_RegionMapper which returns test data for getFormSelectData().
Sjoerd