Chinaunix首页 | 论坛 | 博客
  • 博客访问: 589922
  • 博文数量: 207
  • 博客积分: 10128
  • 博客等级: 上将
  • 技术积分: 2440
  • 用 户 组: 普通用户
  • 注册时间: 2004-10-10 21:40
文章分类

全部博文(207)

文章存档

2009年(200)

2008年(7)

我的朋友

分类:

2009-04-05 11:07:57

When unit testing, you'd also want to test whether your application throws Exceptions as expected (the following examples are based on SimpleTest). Assumption for the examples is, that we have a method that expects an integer as parameter.

First way you probably come up with is this:

  1. try {  
  2.     $class->method('abc');  
  3. } catch(Exception $e) {  
  4.     $this->assertIsA('Exception'$e);  
  5. }  

Generally this looks ok, but it's not. If the method doesn't throw an exception, the test won't fail since the catch block is never executed. That's why we simply drag the test out of the catch block:

  1. try {  
  2.     $class->method('abc');  
  3. } catch(Exception $e) {  
  4. }  
  5. $this->assertIsA('Exception'$e);  
  6. unset($e);  

Now the test fails when the exception isn't thrown because first of all $e won't be set and will surely not be an exception. It is important to add an unset($e), especially if you're testing for more exceptions directly afterwards.

Let's now assume that the method throws an InvalidArgumentException if the given parameter is not an integer.

  1. try {  
  2.     $class->method('abc');  
  3. } catch(Exception $e) {  
  4. }  
  5. $this->assertIsA('InvalidArgumentException'$e);  
  6. unset($e);  

Now the test is in a state where it fails when no exception is thrown or when the thrown exception is not an InvalidArgumentException.

In case you're not lazy on typing, you might add one more line, which also allows you to put the assert back into the catch block:

  1. try {  
  2.     $class->method('abc');  
  3.     $this->fail('Excepted exception was not thrown');  
  4. } catch(Exception $e) {  
  5.     $this->assertIsA('InvalidArgumentException'$e);  
  6. }  
  7. unset($e);  
阅读(635) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~