Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit Testing a PHP Script

I have some php scripts that are run as cronjobs. No classes and only a few functions.

Id like to test the script with PHPUnit to make sure everything is working but it appears I need to rewrite the php as a class, which I dont want to do (or know how to).

For example if I had a script and its only function was to add 1 and 2 together,

 <?php

 $a=1;
 $b=2
 $c=$a+$b;

 ?>

how do I test that $c==3 with phpunit?

Thanks, Don

like image 902
Don F Avatar asked Apr 29 '15 16:04

Don F


1 Answers

For your example, you don't test that $c = 3.

But that is because your example is a little too simplistic. The variable $c stops existing after your script executes. So the fact that it exists doesn't matter. You want to test what your code does, not how it does things.

I will modify your example a little bit:

job.php

<?php

$a=1;
$b=2
echo $a + $b;

?>

Now we actually have some output and some behavior. The test for this would like:

public function testJob() {
   require('job.php');
   $this->expectOutputString('3');
} 

PHPUnit has the ability to assert against stdOut. We make sure that the code outputs what we expect. Your tests for these types of files would check that what they did was correct. Since PHP's require statement will execute the file at the point, we can run the script and check its output.

If your file has functions, you just include that and check each function in their own individual test.

like image 85
Schleis Avatar answered Sep 30 '22 05:09

Schleis