doumaoao0182 2015-07-27 14:44
浏览 68

在使用phpunit抛出异常后执行断言

i started using phpunit and came across this issue im wondering what is the best way to deal with it. I am testing the following function:

/**
 * @expectedException PHPUnit_Framework_Error
 */
function testSetAdsData_dataIsNull()
{
    $dataArr = null;
    $fixture = new AdGroup();
    $fixture->setAdsData($dataArr);

    $this->assertEmpty($fixture->ads);
    $this->assertEmpty($fixture->adIds);
}

now the line $fixture->setAdsData($dataArr); throws an exception as i want and that's ok, but the problem is the following two assertions won't execute. so i read about it and understood that if i want to execute the two following assertions i need to use try/catch , so my question is, what is the correct way to do that? i tried doing this:

/**
 * @expectedException PHPUnit_Framework_Error
 */
function testSetAdsData_dataIsNull()
{
    $dataArr = null;
    $fixture = new AdGroup();
    try{
    $fixture->setAdsData($dataArr);
  } catch (Exception $e){
    $this->assertEmpty($fixture->ads);
    $this->assertEmpty($fixture->adIds);
  }
}

but now the exception is not thrown. should i leave it this way and just remove the expectation part from the top or is there a better way to do that?? thx

  • 写回答

1条回答 默认 最新

  • doubeng9407 2015-07-28 11:36
    关注

    Yes, you need to get rid of the expectedException annotation. You're catching the exception so it won't be thrown now. Indeed, there is another problem: now, if the Exception is not thrown, the test will pass.

    The solution is use a return sentence after the assertions, and making the test fail manually when the Exception is not thrown:

    function testSetAdsData_dataIsNull()
    {
        $dataArr = null;
        $fixture = new AdGroup();
        try {
            $fixture->setAdsData($dataArr);
        } catch (Exception $e){
            $this->assertEmpty($fixture->ads);
            $this->assertEmpty($fixture->adIds);
            return;
        }
        $this->fail('Exception not thrown');
    }
    

    Another recommendation: use Exception subclasses. If an Exception is thrown but not for the reason you expect, the test will pass but maybe the behaviour is not the expected in the real code. If you catch only a certain type of exception, you will be sure that the Exception was raised for the right reason.

    评论

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路