phpunit InvalidArgumentException的测试用例


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;
}

我使用了下面的测试用例,它说,Failed断言抛出了"''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 !');
}

类中的问题是使用empty的检查do:

来自文档

如果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(),'',' ');
    }

希望这能帮助