美文网首页
PHP如何测试exception

PHP如何测试exception

作者: 芒鞋儿 | 来源:发表于2021-02-23 21:06 被阅读0次
  1. 例子程序:
<?php
namespace App\Libraries;

use InvalidArgumentException;

class Calculator
{
    
    public function add($firstnumber, $secondnumber)
    {
        if( !is_numeric($firstnumber) || !is_numeric($secondnumber)){
            throw new \InvalidArgumentException;
        }

        return $firstnumber + $secondnumber;
    }
}
  1. 测试例子:
<?php

use App\Libraries\Calculator;

class CalculatorTest extends PHPUnit\Framework\TestCase
{
    public function setUp(): void
    {
        $this->calculator = new Calculator;
    }
    public function inputNumbers()
    {
        return [
            [2,2,4],
            [2.5,2.5,5],
            [-3,1,-2],
            [-9,-9,-18]
        ];
    }
    /**
     * @dataProvider inputNumbers
     */
    public function testAddNumbers($x,$y,$sum)
    {
        
        $this->assertEquals($sum, $this->calculator->add($x,$y));
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testThrowExceptionIfNonNumbericIsPassed()
    {
        $this->expectException(InvalidArgumentException::class);
        $calc = new Calculator;
        $calc->add('a','b');
        
    }
}

注意两处:

  1. 在注释中写入expectedException 叫做
    注解方式测试exception (use annotation for setting up your test to listen to the exception.)
  2. 在正式测试代码执行之前要加入 $this->expectException(InvalidArgumentException::class);

参考:

  1. https://symfonycasts.com/screencast/phpunit/exceptions-fence-security#play
  2. source code: https://github.com/xieheng0915/test-repo-for-jenkins.git

相关文章

网友评论

      本文标题:PHP如何测试exception

      本文链接:https://www.haomeiwen.com/subject/abedfltx.html