gpt4 book ai didi

InvalidArgumentException 的 phpunit 测试用例

转载 作者:行者123 更新时间:2023-12-05 06:44:26 26 4
gpt4 key购买 nike

请说明如何从下面的函数创建测试用例以测试异常和消息是否正确抛出。我正在使用 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 ValidatorTest extends \PHPUnit_Framework_TestCase{

/**
* @expectedException InvalidArgumentException
* @expectedExceptionMessage Start param is empty !
*/
public function testA()
{
$validator = new Validator();
$validator->validateParams(new Graph(),'',' ');
}

希望对你有帮助

关于InvalidArgumentException 的 phpunit 测试用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28853513/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com