PHP测试,用于过程代码 [英] PHP Testing, for Procedural Code

查看:124
本文介绍了PHP测试,用于过程代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以测试程序代码?我一直在研究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.

每个示例,您都有以下脚本:

Per example, you have this script:

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.

这篇关于PHP测试,用于过程代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆