Testing non OOP PHP

253 views Asked by At

I want to ask is there any way to test procedural code with unit test or any other way.

For example I have below very simple code:

$a = 10;
$b = 20;

for($i = $a; $i < $b; $i++){
    echo 'Loop ' . $i . PHP_EOL;
}

I know that I can check with isset() and other build in functions if the variable exists, also can check type of variable, with output buffering I can get output and count how many times loop was executed, but...can I check if there is for loop not while loop?

I can get whole php file and with regex found it, but maybe there is some kind of magic function that show me that.

1

There are 1 answers

0
dm03514 On BEST ANSWER

For a legacy file that lacks encapsulation, I would recommend testing it at the highest level possible.

For this file is it possible to test it at the webserver level? Which would be a functional test and not a unit test? ie:

  • start up a webserver at the beginning of your test suite
  • make a request to the endpoint that serves the file you posted above
  • assert the content is Loop ...\n ... as expected.

Just asserting on the output and not on the implementation (what kind of loop is used, variables being set, etc.) should allow you to more easily refactor the code, while still having the protection of a test, making sure that the output is as expected.

If the webserver functional test isn't possible, you might be able to create a unit test that captures the output in a similar way:

ob_start();
include 'your_php_file_listed_above';
$out = ob_get_clean();

Then you can assert $out contains Loop .. \n ... correctly.

I would recommend against asserting on implementation specific details, ie which loop is used, which variables are set, as they may slow down refactoring.