文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>Unit Tests: How to test for Exceptions

Unit Tests: How to test for Exceptions

时间:2009-04-05  来源:cobrawgl

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:

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

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:

view plaincopy to clipboardprint?
  1. try {  
  2.     $class->method('abc');  
  3. } catch(Exception $e) {  
  4. }  
  5. $this->assertIsA('Exception', $e);  
  6. unset($e);  
try {
$class->method('abc');
} catch(Exception $e) {
}
$this->assertIsA('Exception', $e);
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.

view plaincopy to clipboardprint?
  1. try {  
  2.     $class->method('abc');  
  3. } catch(Exception $e) {  
  4. }  
  5. $this->assertIsA('InvalidArgumentException', $e);  
  6. unset($e);  
try {
$class->method('abc');
} catch(Exception $e) {
}
$this->assertIsA('InvalidArgumentException', $e);
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:

view plaincopy to clipboardprint?
  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);  
try {
$class->method('abc');
$this->fail('Excepted exception was not thrown');
} catch(Exception $e) {
$this->assertIsA('InvalidArgumentException', $e);
}
unset($e);
相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载