Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use PHPUnit's setExpectedException()?

Tags:

php

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

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?

like image 884
Edward Tanguay Avatar asked Jan 10 '11 11:01

Edward Tanguay


1 Answers

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

    }
}
like image 68
ts. Avatar answered Nov 10 '22 04:11

ts.