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?
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');
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With