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)