John Davidson

phpunit - How to fully cover conditionals while testing code (eg. PHP and xdebug)

0 comments
Message:


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 to if 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. :(



My Answer:
In order to fully cover conditionals while testing code in PHPUnit, you can use code coverage tools like xdebug to help you identify which branches of your code are not being covered by your tests.

One approach you can take is to use xdebug in combination with PHPUnit to generate code coverage reports. This will show you which lines of code are being executed during your tests and which lines are not.

You can also use PHPUnit's data providers feature to test different scenarios for your conditionals. By providing different input values to your tests, you can ensure that all branches of your code are being covered.

Additionally, you can refactor your code to make it more testable. For example, you can extract complex conditionals into separate methods or functions that can be easily tested in isolation.

Overall, the key is to use a combination of code coverage tools, data providers, and refactoring techniques to ensure that your conditionals are fully covered by your tests.

Rate this post

4 of 5 based on 6963 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us