Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPUnit test for error thrown with wrong argument type

Tags:

php

phpunit

I'm just starting with PHPUnit and am ok with all assert* methods, but can't figure out how to test for error thrown when the wrong argument is provided to the method - say hinted with array like so:

public function(array $list) { }

and then tested with null as argument.

Could someone please provide an example of how to test for this sort of errors?

I've checked quite a few posts on stackoverflow, but couldn't find the answer to this specific issue.

Edit

Ok - just to give you an idea of what I'm testing - here's the ArrayHelper::removeIfValueIsEmpty() method:

public static function removeIfValueIsEmpty(array $array) {

    if (empty($array)) {

        return array();

    }

    return array_filter($array, function($value) {

        return !Helper::isEmpty($value);

    });

}

and now test:

class ArrayHelperTest extends PHPUnit_Framework_TestCase {


    public function testRemoveIfValueIsEmpty() {

        $this->assertEmpty(
            \Cmd\Helper\ArrayHelper::removeIfValueIsEmpty(null),
            '\Cmd\Helper\ArrayHelper::removeIfValueIsEmpty method failed (checking with null as argument)'
        );

    }

}

This throws an error:

PHPUnit_Framework_Error : Argument 1 passed to Cmd\Helper\ArrayHelper::removeIfValueIsEmpty() must be of the type array, null given
like image 525
Spencer Mark Avatar asked Oct 21 '25 03:10

Spencer Mark


1 Answers

http://phpunit.de/manual/4.1/en/writing-tests-for-phpunit.html#writing-tests-for-phpunit.errors

/**
* @expectedException PHPUnit_Framework_Error
* @expectedExceptionMessage  Argument 1 passed to Cmd\Helper\ArrayHelper::removeIfValueIsEmpty() must be of the type array, null given
*/
public function testRemoveIfValueIsEmpty() {

    \Cmd\Helper\ArrayHelper::removeIfValueIsEmpty(null);

}
like image 60
Naktibalda Avatar answered Oct 23 '25 18:10

Naktibalda