PHPUnit assert that an exception was thrown?

有谁知道是否有assert或类似的东西可以测试是否在被测试的代码中抛出异常?


<?php
require_once 'PHPUnit/Framework.php';

class ExceptionTest extends PHPUnit_Framework_TestCase
{
    public function testException()
    {
        $this->expectException(InvalidArgumentException::class);
        // or for PHPUnit < 5.2
        // $this->setExpectedException(InvalidArgumentException::class);

        //...and then add your test code that generates the exception 
        exampleMethod($anInvalidArgument);
    }
}

expectException() PHPUnit documentation

PHPUnit author article provides detailed explanation on testing exceptions best practices.


You can also use a docblock annotation:

class ExceptionTest extends PHPUnit_Framework_TestCase
{
    /**
     * @expectedException InvalidArgumentException
     */
    public function testException()
    {
        ...
    }
}

For PHP 5.5+ (especially with namespaced code), I now prefer using ::class


If you're running on PHP 5.5+, you can use ::class resolution to obtain the name of the class with expectException / setExpectedException . This provides several benefits:

  • The name will be fully-qualified with its namespace (if any).
  • It resolves to a string so it will work with any version of PHPUnit.
  • You get code-completion in your IDE.
  • The PHP compiler will emit an error if you mistype the class name.
  • Example:

    namespace MyCoolPackage;
    
    class AuthTest extends PHPUnit_Framework_TestCase
    {
        public function testLoginFailsForWrongPassword()
        {
            $this->expectException(WrongPasswordException::class);
            Auth::login('Bob', 'wrong');
        }
    }
    

    PHP compiles

    WrongPasswordException::class
    

    into

    "MyCoolPackageWrongPasswordException"
    

    without PHPUnit being the wiser.

    Note : PHPUnit 5.2 introduced expectException as a replacement for setExpectedException .

    链接地址: http://www.djcxy.com/p/81712.html

    上一篇: 编译期望异常的错误编译junit测试

    下一篇: PHPUnit断言抛出异常?