使用phpunit测试异常
当我知道将抛出错误时,我正在尝试测试一个函数。函数如下所示:使用phpunit测试异常,php,phpunit,Php,Phpunit,当我知道将抛出错误时,我正在尝试测试一个函数。函数如下所示: function testSetAdsData_dataIsNull(){ $dataArr = null; $fixture = new AdGroup(); try{ $fixture->setAdsData($dataArr); } catch (Exception $e){ $this->assertEquals($e
function testSetAdsData_dataIsNull(){
$dataArr = null;
$fixture = new AdGroup();
try{
$fixture->setAdsData($dataArr);
} catch (Exception $e){
$this->assertEquals($e->getCode(), 2);
}
$this->assertEmpty($fixture->ads);
$this->assertEmpty($fixture->adIds);
}
/**
* @expectedException dataIsNull
*/
function testSetAdsData_dataIsNull(){
$dataArr = null;
$fixture = new AdGroup();
$this->setExpectedException('dataIsNull');
$fixture->setAdsData($dataArr);
$this->assertEmpty($fixture->ads);
$this->assertEmpty($fixture->adIds);
}
but obviously it didn't work and i got this error:
1) adGroupTest::testSetAdsData_dataIsNull
ReflectionException: Class dataIsNull does not exist
现在我尝试使用phpunit异常断言方法来替换try-catch部分,但我不知道如何做到这一点。
我读了很多书,包括这篇文章,但我真的不明白它是如何实现的
我试过这样的方法:
function testSetAdsData_dataIsNull(){
$dataArr = null;
$fixture = new AdGroup();
try{
$fixture->setAdsData($dataArr);
} catch (Exception $e){
$this->assertEquals($e->getCode(), 2);
}
$this->assertEmpty($fixture->ads);
$this->assertEmpty($fixture->adIds);
}
/**
* @expectedException dataIsNull
*/
function testSetAdsData_dataIsNull(){
$dataArr = null;
$fixture = new AdGroup();
$this->setExpectedException('dataIsNull');
$fixture->setAdsData($dataArr);
$this->assertEmpty($fixture->ads);
$this->assertEmpty($fixture->adIds);
}
but obviously it didn't work and i got this error:
1) adGroupTest::testSetAdsData_dataIsNull
ReflectionException: Class dataIsNull does not exist
我做错了什么?如果抛出了异常plz,我如何准确地断言 对于这种情况,我通常使用
@expectedException
注释。见:
检查$fixture->ads
是否真的为null并不能在此处相加,您可以在实际触发异常的调用之前添加这些断言:
$this->assertNull($fixture->ads);
$fixture->setAdsData($dataArr);//throws exception
您正在进行单元测试。这个测试有一个明确的目的:它确保在给定的情况下抛出异常。如果是,那么测试就到此结束
不过,如果您想保持那些assertEmpty
调用,您可以这样做:
try {
$fixture->setAdsData($dataArr);
$e = null;
} cathc (Exception $e) {}
$this->assertEmpty($fixture->ads);
$this->assertEmpty($fixture->adIds);
if (!$e instanceof \Exception) {
//if the exception is not thát important:
$this->markTestIncomplete('No Exception thrown');
//do other stuff here... possibly
$this->fail('The exception was not thrown');
}
throw $e;//throw exception a bit later
另一种方法是手动调用$this->setExpectedException
。由于我们似乎不知道/不关心异常消息的外观,因此我将使用setExpectedExceptionRegExp
方法:
$fixture = new AdGroup();
$this->setExpectedExceptionRegExp(
//exception class, message regex, exception code
'Exception', '/.*/'. 2
);
$fixture->setAdsData(null);//passing null seems to be what you're doing anyway
感谢@Elias Van Ootegem的帮助…为了确保继续执行测试,我需要使用try-catch,无论如何???@Donovenally:一点也不。如果在引发异常的调用之后不添加那些
$this->assertEmpty()
调用,则只需要第一个代码段。任何地方都没有试捕,测试应该是成功的