doulu4976 2010-03-11 00:10
浏览 41
已采纳

为什么PHPUnit在期待异常时会忽略断言?

I have a simple unit test case (extensive question here) on a configuration class that by design triggers PHP errors on type mismatches and undefined configuration settings. In addition to the error, the method is exited returning false.

In my test case, I want to have a number of tests that fail. Trouble is, I can't do a simple 'assert' on the return value: Every error thrown during running a test will be converted into a PHPUnit_Framework_Error exception.

Now I can make PHPUnit aware that I am expecting an error:

/**
 * @expectedException PHPUnit_Framework_Error
 */

public function testSetInvalidKey()
 {
     $this->assertEquals(true, conf::set("invalid_key", "12345"));     
 } 

This works fine, but what I don't understand is that any additional assertion within that function will not be evaluated. Whether it would fail or not, PHPUnit seems to only wait for the exception to happen, and be satisfied with the whole function when it has happened.

To wit, this test will run OK:

/**
 * @expectedException PHPUnit_Framework_Error
 */

 public function testSetInvalidKey()
 { 
   // The error will be triggered here
   $this->assertEquals(true, conf::set("invalid_key", "12345"));                      
   $this->assertEquals(12345, 67810);   // Huh?    
   $this->assertEquals("abc", "def");   // Huh?
   $this->assertEquals(true, false);    // Huh?

 }

Why? Is this the intended behaviour?

I realize you would just separate the assertions into different functions, but I would like to understand the behaviour.

  • 写回答

2条回答 默认 最新

  • douyan1882 2010-03-11 03:17
    关注

    Since conf::set() is executed within the method testSetInvalidKey() the corresponding catch block must be outside. Once caught and logged as the expected exception, I don't see how PHP could resume execution after the first assertion.

    Extreme psuedo-code:

    class Tester
    {
      public function run()
      {
        try {
          $test->testSetInvalidKey();
        }
        catch (PHPUnit_Framework_Error $e) {
          // Expected exception caught! Woohoo!
          // How can I continue to run the above method where I left off?
        }
      }
    }
    

    This type of behavior would be a great proponent to those who believe in the 1 assertion per test axiom.

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

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP