我是单元测试的新手,编写了以下测试:
/**
* @expectedException Exception
*/
public function testCantGetInvalidCampsite() {
$invalidIds = array(300000, "string");
foreach($invalidIds as $id) {
$this->campsites->getCampsite($id); // will throw an exception
}
}
我不确定这是否真的在测试所有无效的 ID,或者只是在遇到第一个异常时立即停止。这是我应该如何测试多个异常,还是我需要将其分成许多不同的测试,或者我应该采用另一种方法吗?
此外,如果我的异常消息是动态生成的,例如“无法检索 ID 为 30000 的记录”,我该如何测试是否生成了正确的动态消息?
最佳答案
我在这种情况下使用的方法是使用 phpunit dataProviders :
class MyTest extends PHPUnit_Framework_TestCase
{
public function invalidIds()
{
return array(
array(300000),
array("string")
);
}
/**
* @dataProvider invalidIds
* @expectedException Exception
*/
public function testCantGetInvalidCampsite($invalidId)
{
$this->campsites->getCampsite($invalidId); // will throw an exception
}
}
关于unit-testing - 使用 phpunit 测试多个异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4314142/