请告诉如何从下面的函数中创建测试用例来测试异常并正确抛出消息。我用的是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 !');
}发布于 2015-03-04 11:54:32
您的类中的问题是使用empty进行的检查:
来自文档
如果var存在且具有非空的非零值,则返回FALSE .否则返回TRUE。
此测试对于您的验证器类(绿色栏)很好:
class ValidatorTest extends \PHPUnit_Framework_TestCase{
/**
* @expectedException InvalidArgumentException
* @expectedExceptionMessage Start param is empty !
*/
public function testA()
{
$validator = new Validator();
$validator->validateParams(new Graph(),'',' ');
}希望能帮上忙
https://stackoverflow.com/questions/28853513
复制相似问题