PHP Testing, for Procedural Code

依然范特西╮ 提交于 2019-12-20 09:31:08

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/5021254/php-testing-for-procedural-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!