如何使用PHPUnit的setExpectedException()? [英] How to use PHPUnit's setExpectedException()?

查看:70
本文介绍了如何使用PHPUnit的setExpectedException()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用PHPUnit,我可以成功测试,如果对类的特定调用正确抛出了这样的异常:

With PHPUnit I can successfully test if a specific call to a class properly throws an exception like this:

try 
{
    $dummy = Import_Driver_Excel::get_file_type_from_file_name('BAD_NAME.nnn');   
}
catch (Exception $ex) 
{
    return;
}
$this->fail("Import_Driver_Excel::get_file_type_from_file_name() does not properly throw an exception");

但是我阅读了

But I read here that there is a simpler way, basically in one line using setExpectedException():

class ExceptionTest extends PHPUnit_Framework_TestCase
{
    public function testException()
    {
        $this->setExpectedException('InvalidArgumentException');
    }
}

但是如何使它像上面的示例那样工作,即我想仅在我使用'BAD_NAME.nnn'进行特定调用时测试该类是否抛出此异常?变体不起作用:

But how do I get it to work as in the above example, i.e. I want to test that the class throws this exception only when I make the specific call with 'BAD_NAME.nnn'? These variants don't work:

$dummy = Import_Driver_Excel::get_file_type_from_file_name('BAD_NAME.nnn');  
$this->setExpectedException('Exception');

也不是:

$this->setExpectedException('Exception');
$dummy = Import_Driver_Excel::get_file_type_from_file_name('BAD_NAME.nnn'); 

如何使用setExpectedException()替换上面的工作示例?

推荐答案

您可以使用 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆