PHP如何测试exception

2021-02-23  本文已影响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
上一篇下一篇

猜你喜欢

热点阅读