且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PHPUnit断言抛出异常?

更新时间:2023-11-16 08:54:34

http://phpunit.de/manual/current/en/writing-tests-for-phpunit.html#writing-tests-for-phpunit。 exceptions.examples.ExceptionTest.php

 <?php 
require_once'PHPUnit / Framework.php ;

class ExceptionTest扩展PHPUnit_Framework_TestCase
{
public function testException()
{
$ this-> expectException(InvalidArgumentException :: class);
//或PHPUnit 5.2
// $ this-> setExpectedException(InvalidArgumentException :: class);

//...然后添加生成异常的测试代码
exampleMethod($ anInvalidArgument);
}
}


Does anyone know whether there is an assert or something like that which can test whether an exception was thrown in the code being tested?

http://phpunit.de/manual/current/en/writing-tests-for-phpunit.html#writing-tests-for-phpunit.exceptions.examples.ExceptionTest.php

<?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);
    }
}