awaken

博客园 首页 新随笔 联系 订阅 管理

Testing Exceptions

 

@expectedException声明用来测试测试代码中指定异常是否被抛出
代码
 1<?php
 2require_once 'PHPUnit/Framework.php';
 3 
 4class ExceptionTest extends PHPUnit_Framework_TestCase
 5{
 6    /**
 7     * @expectedException InvalidArgumentException
 8     */
 9    public function testException()
10    {
11    }
12}
13?>

phpunit ExceptionTest
PHPUnit 3.4.2 by Sebastian Bergmann.

F

Time: 0 seconds

There was 1 failure:

1) testException(ExceptionTest)
Expected exception InvalidArgumentException

FAILURES!
Tests: 1, Assertions: 1, Failures: 1.

另外,你也可以使用setExpectedException()来设置期望抛出的异常
代码
 1<?php
 2require_once 'PHPUnit/Framework.php';
 3 
 4class ExceptionTest extends PHPUnit_Framework_TestCase
 5{
 6    public function testException()
 7    {
 8        $this->setExpectedException('InvalidArgumentException');
 9    }
10}
11?>

phpunit ExceptionTest
PHPUnit 3.4.2 by Sebastian Bergmann.

F

Time: 0 seconds

There was 1 failure:

1) testException(ExceptionTest)
Expected exception InvalidArgumentException

FAILURES!
Tests: 1, Assertions: 1, Failures: 1.

Testing PHP Errors
默认设置下,PHPUnit把执行中触发的error,warning,notice都转化成一个exception.
代码
 1<?php
 2class ExpectedErrorTest extends PHPUnit_Framework_TestCase
 3{
 4    /**
 5     * @expectedException PHPUnit_Framework_Error
 6     */
 7    public function testFailingInclude()
 8    {
 9        include 'not_existing_file.php';
10    }
11}
12?>

phpunit ExpectedErrorTest
PHPUnit 3.4.2 by Sebastian Bergmann.

.

Time: 0 seconds

OK (1 test, 1 assertion)
posted on 2009-11-27 10:24  awaken  阅读(1301)  评论(0)    收藏  举报