1

I have started playing with PHPUnit and am quite perplexed with a foreach statement. I have created a simple function:

public function testForEach(array $x): void {
   foreach($x as $k => $v) ; //empty foreach
}

I applied PHPUnit and it says that there are 3 paths in the function. The paths that I know about are:

  1. The empty array []
  2. An single item array, e.g. [1]

I tried to input an array with 2 elements [1, 2] and an associative array ['x' => 1], but the tool states that I have found 2 out of three paths. I even tried [1, 2, 3, 4, 5] to no avail.

Does anyone know what the 3rd path is?

If I change the empty statement to a simple echo $x;, the result is still 3 paths, so it has nothing to do with the empty statement.

Thanks

Alexios Tsiaparas
  • 880
  • 10
  • 17

1 Answers1

2

Traced it back at the PHPUnit level, the library used is phpunit/php-code-coverage.

PHPUnit makes the following checks for a simple foreach loop:

  • The empty array [], exits before entering any commands behaves like an if at the start of loop.
  • At least one pass, in my example [1]. This ensures that the loop is executed at least once.
  • No iterations and no checking, like null in my example. It seems there is a condition at foreach that $x is iterable, and it needs to fail.
Alexios Tsiaparas
  • 880
  • 10
  • 17
  • The condition at foreach that $x is iterable is to test for the error condition. No need to test for that in your own test code, as it is a test in itself already, so you have it automatically asserted. – hakre Jul 15 '23 at 14:19