开发者

How to use PHPUnit's setExpectedException()?

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 s开发者_JS百科impler 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?


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

    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜