免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1401 | 回复: 0
打印 上一主题 下一主题

Unit Tests: How to test for Exceptions [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-04-05 11:07 |只看该作者 |倒序浏览

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 plain
copy to clipboard
print
?
try {  
    $class->method('abc');  
} catch(Exception $e) {  
    $this->assertIsA('Exception', $e);  
}  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 plain
copy to clipboard
print
?
try {  
    $class->method('abc');  
} catch(Exception $e) {  
}  
$this->assertIsA('Exception', $e);  
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 plain
copy to clipboard
print
?
try {  
    $class->method('abc');  
} catch(Exception $e) {  
}  
$this->assertIsA('InvalidArgumentException', $e);  
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 plain
copy to clipboard
print
?
try {  
    $class->method('abc');  
    $this->fail('Excepted exception was not thrown');  
} catch(Exception $e) {  
    $this->assertIsA('InvalidArgumentException', $e);  
}  
unset($e);  try {
    $class->method('abc');
    $this->fail('Excepted exception was not thrown');
} catch(Exception $e) {
    $this->assertIsA('InvalidArgumentException', $e);
}
unset($e);


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/78/showart_1890526.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP