2023-07-16

PHP and PHPUnit: How to invoke method (or function) with wrong parameter type and then to success?

I want to test (with PHPUnit) a method that contains a foreach loop. I want the full path coverage. The original code is little too complex, so I created a minimal example below to illustrate my problem. There are 3 cases for the foreach loop in the PHP. (I use PHP 8.2.)

  1. Empty iterable something.
  2. Not empty iterable something.
  3. Not iterable something.
    public function dodo(array $a)
    {
        foreach ($a as $one) {
            return $one;
        }

        return null;
    }

It is easy to cover first two: a not empty array and an empty array. But how can I pass a not iterable something as the function argument? I have tried few ways, but I’ve got the TypeError.

$something->dodo(null); # TypeError

call_user_func([$something, 'dodo'], null); # TypeError

$rClass = new ReflectionClass($something);
$rMethod = $rClass->getMethod('dodo');
$rMethod->invoke($something, null); # TypeError

I don’t want to remove or change the type from the method definition. This would make the code a little less readable. Is there a way around? How can I write a test that will cover all cases of the foreach loop?

In other words: How i can call the dodo with an argument of a wrong type? I want to write test with very high code paths coverage.



No comments:

Post a Comment