Some time ago I have started writing tests in PHPUnit (v. 9). It’s great and amazing but:
How I can properly cover conditionals?
I will give some examples where result is correct and expected, and where I see problems. Here it is:
Please note that code below is only the sample.
I know that when I pass
true
toif
statement there will be no chance to go to other branch of code. It’s only the example as plain as possible.
Situation where problem does not exits:
if (true) { return 'true';//here is covered } return 'false';//here is not covered
And this is ok, however below:
return (true) ? 'true' : 'false';
Whole line is treated as covered, but is obvious that false will never be returned.
So. What am I doing bad?
Only solution is not to use ternary operator? Its very short syntax, but error-prone because of lack of (real / false) information about coverage. 🙁
Advertisement
Answer
The default view in PHP Unit is indeed line coverage, and hence, as you indicate can’t distinguish both branches in the single line ternary case.
However, more recently PHPUnit also has branch and path coverage.
It shows this in the output left of “Lines”. In order to see which branches are missing, you can hover over a line in the source view that is yellow, and it will tell you that (in my example) only 3 out of 4 possible paths have been followed.
The author of this feature also wrote an extensive explanation on his blog.