问题
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