4

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
5
  • we couldn't provide the help without complete description of your post with an example. you have to specify more Commented Aug 20, 2014 at 10:12
  • Well - there is an example - you have a public method with array type of the argument - and you want to test for null, but I don't know how to perform this test - hence the question. What else do you want me to put here? Commented Aug 20, 2014 at 10:13
  • Have you looked at PHPUnit's annotations? In particular @expectedexception. Having said that; why are you testing this? It is built in behaviour for PHP. You should be testing your code, not the language.
    – vascowhite
    Commented Aug 20, 2014 at 10:14
  • pass an empty array to your function? Commented Aug 20, 2014 at 10:14
  • nope - pass 'null' as argument in test Commented Aug 20, 2014 at 10:15

1 Answer 1

6

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);

}
2
  • Done, but I would call this testcase testIfMethodHasArrayTypeHint.
    – Naktibalda
    Commented Aug 20, 2014 at 10:30
  • Thanks - yeah, probably better name for the test. Commented Aug 20, 2014 at 10:32

Not the answer you're looking for? Browse other questions tagged or ask your own question.