PHP 测试,用于程序代码

2022-01-25 00:00:00 testing php phpunit procedural

有什么方法可以测试程序代码吗?我一直在研究 PHPUnit,这似乎是一种创建自动化测试的好方法.但是,它似乎是面向面向对象的代码,有没有其他程序代码的替代品?

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.

谢谢,

丹尼尔.

推荐答案

您可以使用 PHPUnit 测试程序代码.单元测试不依赖于面向对象的编程.他们测试代码单元.在 OO 中,一个代码单元就是一个方法.在程序 PHP 中,我猜它是一个完整的脚本(文件).

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

虽然 OO 代码更易于维护和测试,但这并不意味着无法测试过程式 PHP.

While OO code is easier to maintain and to test, that doesn't mean procedural PHP cannot be tested.

例如,你有这个脚本:

simple_add.php

$arg1 = $_GET['arg1'];
$arg2 = $_GET['arg2'];
$return = (int)$arg1 + (int)$arg2;
echo $return;

你可以这样测试:

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
    }

}

对于这个例子,我声明了一个 _execute 方法,它接受一个 GET 参数数组,捕获输出并返回它,而不是一遍又一遍地包含和捕获.然后我使用 PHPUnit 的常规断言方法比较输出.

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.

当然,第三个断言会失败(尽管取决于 error_reporting),因为被测试的脚本会给出 未定义索引 错误.

Of course, the third assertion will fail (depends on error_reporting though), because the tested script will give an Undefined index error.

当然,测试的时候应该把error_reporting放到E_ALL |E_STRICT.

Of course, when testing, you should put error_reporting to E_ALL | E_STRICT.

相关文章