如何测试 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用 PHPUnit 测试程序代码。单元测试与面向对象编程无关。 他们测试代码单元。在面向对象中,代码单元是方法。在程序化 PHP 中,我猜它是一个完整的脚本(文件)。
虽然 OO 代码更容易维护和测试,但这并不意味着过程 PHP 无法测试。
例如,您有以下脚本:
simple_add.php
您可以像这样测试它:
对于此示例,我声明了一个接受 GET 参数数组的
_execute
方法,捕获输出并返回它,而不是一遍又一遍地包含和捕获。然后,我使用 PHPUnit 的常规断言方法来比较输出。当然,第三个断言将失败(尽管取决于 error_reporting),因为测试的脚本将给出 未定义索引 错误。
当然,测试的时候,应该把error_reporting放到
E_ALL | E_STRICT
。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
You could test it like this:
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
.