How to use PHPUnit's setExpectedException()?

拜拜、爱过 提交于 2019-12-21 15:24:19

问题


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');
    }
}

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');

nor this:

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

How do I use setExpectedException() to replace my working example above?


回答1:


You can use expectedException annotation:

class ExceptionTest extends PHPUnit_Framework_TestCase
{
    /**
     * @expectedException InvalidArgumentException
     */
    public function testException()
    {
        $dummy = Import_Driver_Excel::get_file_type_from_file_name('BAD_NAME.nnn');

    }
}


来源:https://stackoverflow.com/questions/4646298/how-to-use-phpunits-setexpectedexception

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!