Is there any way of testing procedural code? I have been looking at PHPUnit which seems like a great way of creating automated tests. However, it seems to be geared towards object oriented code, are there any alternatives for procedural code?
Or should I convert the website to object oriented before attempting to test the website? This may take a while which is a bit of a problem as I don't have a lot of time to waste.
Thanks,
Daniel.
PHPUnit is a unit testing framework for the PHP programming language. It is an instance of the xUnit design for unit testing systems that began with SUnit and became popular with JUnit. Even a small software development project usually takes hours of hard work.
In the PHP Explorer, right-click the file, and select New | PHPUnit Test Case. The New PHPUnit Test Case dialog is displayed. To select the element to be tested, click Browse next to the Tested Element field. The Element selection dialog is displayed.
Codeception is a framework used for creating tests, including unit tests, functional tests, and acceptance tests. Despite the fact that it is based on PHP, the user needs only basic knowledge for starting work with the framework, thanks to the set of custom commands offered by Codeception.
You can test procedural code with PHPUnit. Unit tests are not tied to object-oriented programming. They test units of code. In OO, a unit of code is a method. In procedural PHP, I guess it's a whole script (file).
While OO code is easier to maintain and to test, that doesn't mean procedural PHP cannot be tested.
Per example, you have this script:
simple_add.php
$arg1 = $_GET['arg1']; $arg2 = $_GET['arg2']; $return = (int)$arg1 + (int)$arg2; echo $return;
You could test it like this:
class testSimple_add extends PHPUnit_Framework_TestCase { private function _execute(array $params = array()) { $_GET = $params; ob_start(); include 'simple_add.php'; return ob_get_clean(); } public function testSomething() { $args = array('arg1'=>30, 'arg2'=>12); $this->assertEquals(42, $this->_execute($args)); // passes $args = array('arg1'=>-30, 'arg2'=>40); $this->assertEquals(10, $this->_execute($args)); // passes $args = array('arg1'=>-30); $this->assertEquals(10, $this->_execute($args)); // fails } }
For this example, I've declared an _execute
method that accepts an array of GET parameters, capture the output and return it, instead of including and capturing over and over. I then compare the output using the regular assertions methods from PHPUnit.
Of course, the third assertion will fail (depends on error_reporting though), because the tested script will give an Undefined index error.
Of course, when testing, you should put error_reporting to E_ALL | E_STRICT
.
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