Home > Backend Development > PHP Tutorial > [PHP]PHPUnit入门之三

[PHP]PHPUnit入门之三

WBOY
Release: 2016-06-23 14:31:57
Original
922 people have browsed it

Testing Exceptions

 

@expectedException声明用来测试测试代码中指定异常是否被抛出

代码

 1 php
 2 require_once   ' PHPUnit/Framework.php ' ;
 3  
 4 class  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
 2 require_once   ' PHPUnit/Framework.php ' ;
 3  
 4 class  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
 2 class  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)
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template