摘要:本文将带你了解软件测试技术之单元测试系列二:单元测试如何测试异常与超时,希望本文对大家学测试技术有所帮助。
一、 测试异常
1. 使用@test的expected属性测试异常
// 第一种方式, 使用expected属性
@Test(expected = FileNotFoundException.class)
public void usingExpected() throws FileNotFoundException {
// 不会抛出FileNotFoundException的代码写在上面
new FileInputStream("不存在的文件路径");
2.
使用try/catch,fail的方式测试异常
// 第二种方式, 使用try/catch和fail方法
@Test
public void usingTryCatchAndFail() {
// 其他代码
try {
new FileInputStream("不存在的文件路径");
fail("前面的代码已经抛出FileNotFoundException!");
} catch (FileNotFoundException e) {
assertTrue(e.getMessage().contains("不存在的文件路径"));
}
}
3.
使用@Rule,expectedException的方式测试异常
// 第三种方式, 使用ExpectedException规则
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void shouldTestExceptionMessage() throws FileNotFoundException {
thrown.expect(FileNotFoundException.class);
thrown.expectMessage("不存在的文件路径");
thrown.expectMessage("存在");
thrown.expectMessage("文件路径");
new FileInputStream("不存在的文件路径");
}
二、 测试超时
1. 使用@test的timeout属性测试超时
// 第一种方式,使用timeout属性
@Test(timeout=1000)
public void timeoutIn1Seconds(){
System.out.println("一秒钟超时");
while(true){}
}
2.
使用@rule,timeout的方式测试超时
// 第二种方式,使用Timeout规则
@Rule
public Timeout globalTimeout=new Timeout(5000);
//Timeout.seconds(5);//这个 <code>seconds</code>方法只在JUnit 4.12版本之后才有效
@Test
public void timeoutIn5Seonds(){
System.out.println("五秒钟超时");
while(true){}
}
本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标软件测试之测试技术频道!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号