InvalidArgumentException 的 phpunit 测试用例
phpunit Test cases for InvalidArgumentException
请说明如何从下面的函数创建测试用例以测试异常和消息是否正确抛出。我正在使用 Symfony 2.
public function validateParams(Graph $graph, $start, $destination)
{
if (!is_object($graph)) {
throw new \InvalidArgumentException('Graph param should be an object !');
}
if (empty($start)) {
throw new \InvalidArgumentException('Start param is empty !');
}
if (empty($destination)) {
throw new \InvalidArgumentException('Graph param is empty !');
}
return true;
}
我在下面使用了测试用例,它说,无法断言抛出“\InvalidArgumentException”类型的异常。
/**
* @expectedException \InvalidArgumentException
*/
public function testValidateParamsWhenStartingPointIsEmpty()
{
$this->shortestPathCalc= new ShortestPathCalculator();
$this->shortestPathCalc->validateParams($this->graph, ' ', 'f', 'Expected exception not thrown when starting point is empty !');
}
你的 class 中的问题是 empty
的检查是:
来自doc
Returns FALSE if var exists and has a non-empty, non-zero value.
Otherwise returns TRUE.
此测试对您的验证器工作正常 class(绿色条):
class ValidatorTest extends \PHPUnit_Framework_TestCase{
/**
* @expectedException InvalidArgumentException
* @expectedExceptionMessage Start param is empty !
*/
public function testA()
{
$validator = new Validator();
$validator->validateParams(new Graph(),'',' ');
}
希望对您有所帮助
请说明如何从下面的函数创建测试用例以测试异常和消息是否正确抛出。我正在使用 Symfony 2.
public function validateParams(Graph $graph, $start, $destination)
{
if (!is_object($graph)) {
throw new \InvalidArgumentException('Graph param should be an object !');
}
if (empty($start)) {
throw new \InvalidArgumentException('Start param is empty !');
}
if (empty($destination)) {
throw new \InvalidArgumentException('Graph param is empty !');
}
return true;
}
我在下面使用了测试用例,它说,无法断言抛出“\InvalidArgumentException”类型的异常。
/**
* @expectedException \InvalidArgumentException
*/
public function testValidateParamsWhenStartingPointIsEmpty()
{
$this->shortestPathCalc= new ShortestPathCalculator();
$this->shortestPathCalc->validateParams($this->graph, ' ', 'f', 'Expected exception not thrown when starting point is empty !');
}
你的 class 中的问题是 empty
的检查是:
来自doc
Returns FALSE if var exists and has a non-empty, non-zero value. Otherwise returns TRUE.
此测试对您的验证器工作正常 class(绿色条):
class ValidatorTest extends \PHPUnit_Framework_TestCase{
/**
* @expectedException InvalidArgumentException
* @expectedExceptionMessage Start param is empty !
*/
public function testA()
{
$validator = new Validator();
$validator->validateParams(new Graph(),'',' ');
}
希望对您有所帮助