Misleading Code Coverage Reports for Switch Statements

I was recently investigating the code coverage of theĀ map_meta_cap() function in WordPress’ core unit test suite — particularly the large switch statement contained within the function. I was surprised to see that the coverage was higher than I was expecting, because I know for a fact that several meta capabilities aren’t tested.

It turns out there is a subtle code coverage reporting issue for switch statements that allow multiple conditions to trigger one action.

Example:

switch ( $condition ) {
	case 1:
	case 2:
		echo $condition;
		break;
}

Given a value of 2 for $condition in a test that covers this code, the code coverage report tells us that this code has complete coverage:

Misleading Code Coverage Report

This is not the case though. The code within the action for the condition is indeed being exercised, but only with a value of 2. If we refactor this code so there’s one action per condition and re-run the test, we can see that the action is not being exercised with a value of 1:

switch ( $condition ) {
	case 1:
		echo $condition;
		break;
	case 2:
		echo $condition;
		break;
}

The code coverage report is now more accurate:

More Accurate Code Coverage Report

This sort of code coverage reporting issue isn’t confined to switch statements with multiple actions per condition, of course, but it may be more subtle than other code coverage issues, especially with code more complex than the examples above.

Leave a Reply

Your email address will not be published. Required fields are marked *