duanfu7994 2010-03-09 13:40
浏览 34
已采纳

单元测试类 - 抛出错误是不可能的?

I am getting my head around PHPUnit, and trying to build a test case for an existing class.

The class is a static configuration class, getting, setting and listing configuration options that will be available in the application.

The class is very strictly built. If I try to set a configuration setting with an incompatible value, or a configuration setting that does not exist, a E_USER_ERROR is thrown, halting the execution of the script. Even if it's not the fine art of error handling, it works fine for the purposes of this class. An error in that class is always the result of a programming error, and never of bad user input.

This has the great advantage that you don't have to worry about how error messages are handled or logged, which keeps the code slim. Output the message (or not, in production), die(), done.

However, with Unit tests, I don't see how I can continue to work with classic PHP errors. I will have to convert the functions to return success flags, or throw exceptions.

Am I correct?

Or is there a way in PHPUnit to expect errors, as there is to expect Exceptions? I can't see any straight away.

  • 写回答

4条回答 默认 最新

  • douruyun8153 2010-03-09 14:09
    关注

    From the PHPUnit manual:

    By default, PHPUnit converts PHP errors, warnings, and notices that are triggered during the execution of a test to an exception. Using these exceptions, you can, for instance, expect a test to trigger a PHP error as shown in Example 4.8.

    class ExpectedErrorTest extends PHPUnit_Framework_TestCase
    {
        /**
         * @expectedException PHPUnit_Framework_Error
         */
        public function testFailingInclude()
        {
            include 'not_existing_file.php';
        }
    }
    

    Same works for exceptions of course.

    Edit: didn't see this was already mentioned in the comments, but I'll leave it here for reference in case someone looks for the same question and doesn't read the comments

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 hexo+github部署博客
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?