6

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?

5
  • 5
    Your second example is the correct. Can you point out what's not working.
    – Gordon
    Commented Jan 10, 2011 at 11:32
  • $this->setExpectedException('Exception'); throw new Exception(); -- what if you perform this code?
    – zerkms
    Commented Jan 10, 2011 at 11:37
  • It does indeed work as in the second example, thanks. Commented Jan 10, 2011 at 11:38
  • well, follow this template then: a) set expectations b) run test methods c) PROFIT!!!1 ;-)
    – zerkms
    Commented Jan 10, 2011 at 11:39
  • You could use the comment annotation also. phpunit.de/manual/current/en/…
    – joksnet
    Commented Jan 10, 2011 at 11:49

1 Answer 1

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

    }
}
1
  • 9
    Wait, does this solve the problem? I thought OP was concerned about getting false positives from exceptions thrown by code other than the BAD_NAME call. The annotation doesn't narrow this down.
    – DSimon
    Commented Jan 25, 2013 at 19:02

Not the answer you're looking for? Browse other questions tagged or ask your own question.