문제

I have a basic ZF2 InputFilter that I created. How exactly do I test it with PHPUnit without attaching it to a Form?

I can't find any sample on how this is done. Hope someone can help out.

도움이 되었습니까?

해결책

I usually have a data provider to test my input filters.

Here's an example input filter with two really simple fields:

use Zend\InputFilter\InputFilter;
use Zend\InputFilter\Input;
use Zend\I18n\Validator\Alnum;

class MyInputFilter extends InputFilter
{
    public function __construct()
    {
        $name = new Input('name');

        $name->setRequired(false)->setAllowEmpty(true);
        $this->add($name);

        $nickname = new Input('nickname');

        $nickname->getValidatorChain()->attach(new Alnum());
        $this->add($nickname);
    }
}

And here's a test class for it:

class MyInputFilterTest extends \PHPUnit_Framework_TestCase
{
    public function setUp()
    {
        $this->inputFilter = new MyInputFilter();
    }

    /** @dataProvider validatedDataProvider */
    public function testValidation($data, $valid)
    {
        $this->inputFilter->setData($data);
        $this->assertSame($valid, $this->inputFilter->isValid());
    }

    public function validatedDataProvider()
    {
        return array(
            array(
                array(),
                false
            ),
            array(
                array('name' => '', 'nickname' => 'Ocramius'),
                true
            ),
            array(
                array('name' => 'Test', 'nickname' => 'Ocramius'),
                true
            ),
            array(
                array('name' => 'Test', 'nickname' => 'Hax$or'),
                false
            ),
        );
    }
}

This is a very simple example, but I am basically throwing different datasets at the filter and checking what is relevant to me (in this case checking that data is valid or invalid).

If your filter applies transformations on the data, you may also want to check what the output of $inputFilter->getValues() is.

If the error messages are relevant to you, you can also check $inputFilter->getMessages().

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top