PHPUnit针对InvalidArgumentException的测试用例

3

请告诉我如何创建测试用例以测试异常和消息是否正确抛出。我使用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 !');
}

2
似乎是因为''不被视为一个空值。请参考文档 - Matteo
1个回答

1
你的类中存在的问题是使用 empty 检查:
doc 中得知:

如果变量存在且具有非空、非零值,则返回 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(),'',' ');
    }

希望这有所帮助。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接