开发者

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

开发者 https://www.devze.com 2023-01-03 16:08 出处:网络
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 retrieves them from the d开发者_如何转开发atabase.

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 retrieves them from the d开发者_如何转开发atabase.

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?


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().


I agree with Sjoerd, as in this case you're testing your form, not how the data is retrieved, just create a mock object and set it's return value with information which you would expect to receive in that situation. A good alternative to PHPUnit Mock Objects is Mockery by Padraic O'Brady. It's a drop in alternative.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号