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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With