dongyue8640 2015-03-04 11:40
浏览 97
已采纳

phpunit InvalidArgumentException的测试用例

Please tell how to create test cases fro below function to test exception and messages is thrown correctly. I'm using 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;
}

I used below test case and it says, Failed asserting that exception of type "\InvalidArgumentException" is thrown.

 /**
 * @expectedException \InvalidArgumentException
 */
public function testValidateParamsWhenStartingPointIsEmpty()
{
   $this->shortestPathCalc= new ShortestPathCalculator();
   $this->shortestPathCalc->validateParams($this->graph, ' ', 'f', 'Expected exception not thrown when starting point is empty !');
}
  • 写回答

1条回答 默认 最新

  • dongmiyi8220 2015-03-04 11:54
    关注

    The problem in your class is that the check with empty do:

    From the doc

    Returns FALSE if var exists and has a non-empty, non-zero value. Otherwise returns TRUE.

    This test work fine for your validator class (green bar):

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

    Hope this help

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器