Zend 2:表单类的单元测试

use*_*508 7 phpunit zend-framework2

我刚刚开始在Zend中使用PHPUnit,并且无需帮助弄清楚这些测试应该如何工作.

如果我没有传递任何POST参数,我想测试表单是否返回任何错误消息.

问题是我的表单中的一个字段是使用Doctrine的 DoctrineModule\Form\Element\ObjectSelect

    ...
    $this->add(array(
        'type' => 'DoctrineModule\Form\Element\ObjectSelect',
        'name' => 'user',
        'attributes' => array(
            'id' => 'user-label',
        ),
        'options' => array(
            'object_manager' => $em,
            'target_class' => 'Application\Entity\User',
            'property' => 'username',
            'label' => 'User:',
            'display_empty_item' => true,
            'empty_item_label'   => '---',
            'label_generator' => function($entity) {
                return $entity->getUsername();
            },
        ),
    ));
    ...
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:
Fatal error: Call to a member function getIdentifierFieldNames() on null

我尝试使用模拟对象覆盖此字段,但是Zend不允许objects输入type,只是类名(string),因此此代码不起作用:

public function testIfFormIsValid()
{
    $objectSelect = $this->getMockBuilder('DoctrineModule\Form\Element\ObjectSelect')
        ->disableOriginalConstructor()
        ->getMock();
    $objectSelect->expects($this->any())
        ->method('getValueOptions')
        ->will($this->returnValue(array()));

    $form = new \AppModuleComment\Form\Comment('form', array(
        'em' => $this->em  // Mocked object
    ));
    $form->add(array(
        'type' => $objectSelect,
        'name' => 'user',
        'attributes' => array(
            'id' => 'user-label',
        ),
        'options' => array(
            'object_manager' => $this->em,
            'target_class' => 'Application\Entity\User',
            'property' => 'username',
            'label' => 'User:',
            'display_empty_item' => true,
            'empty_item_label'   => '---',
            'label_generator' => function($entity) {
                return $entity->getUsername();
            },
        ),
    ));

    $data = array(
        'id' => null,
        'user' => null
    );

    $form->setData($data);
    $this->assertTrue($form->isValid(), 'Form is not valid');
}    
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?我该如何测试这样的代码?

iRa*_*RaS 1

看来您正在测试 Zend 或 Doctrine (或两者)的功能,而不是您自己的代码。当您使用库时,您应该信任这些库。

发生的情况是:Form\Form::add()使用Form\Factory::create()数组创建一个元素。Form\Factory::create()用于Form\FormElementManager::get()从给定类型获取元素。

您的类型是一个对象,并且由于Form\FormElementManager::get()无法处理对象,您的脚本将失败。

您似乎想测试 post 是否为空调Form::valid()ObjectSelect::valid(),但这并不能验证该值是否为空。那是来自 Doctrine / Zend 的代码,不是你的。不要测试它。

当您想模拟 Doctrines 中的选择结果时,它会变得更有趣ObjectSelect。但这是另一个问题了。