有什么方法可以测试程序代码吗?我一直在研究 PHPUnit,这似乎是一种创建自动化测试的好方法。但是,它似乎面向面向对象的代码,是否有任何替代程序代码的方法?
或者我应该在尝试测试网站之前将网站转换为面向对象?这可能需要一段时间,这有点问题,因为我没有太多时间可以浪费。
谢谢,
丹尼尔。
有什么方法可以测试程序代码吗?我一直在研究 PHPUnit,这似乎是一种创建自动化测试的好方法。但是,它似乎面向面向对象的代码,是否有任何替代程序代码的方法?
或者我应该在尝试测试网站之前将网站转换为面向对象?这可能需要一段时间,这有点问题,因为我没有太多时间可以浪费。
谢谢,
丹尼尔。
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
.