Search code examples
phptestingphpunitprocedural

How to test procedural PHP?


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.


Solution

  • 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.