单元测试系列二:单元测试如何测试异常与超时

发表于:2018-7-10 09:40

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:青鱼入云    来源:CSDN

  一、 测试异常
  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){}
  }
上文内容不用于商业目的,如涉及知识产权问题,请权利人联系博为峰小编(021-64471599-8017),我们将立即处理。
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号