phpunitzend-framework2zend-inputfilter

How do I test my Zend Framework 2 InputFilter with PHPUnit?


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.


Solution

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