首页 > 其他 > 详细

Junit 小案例 测试异常

时间:2015-10-20 19:35:41      阅读:290      评论:0      收藏:0      [点我收藏+]

package com.laiwenhua.junitTest;



import static org.junit.Assert.assertTrue;

import static org.junit.Assert.fail;


import java.io.FileInputStream;

import java.io.FileNotFoundException;


import org.junit.Rule;

import org.junit.Test;

import org.junit.rules.ExpectedException;

/**

 * 测试异常

 * @author 绵敏

 *

 */

public class ExceptionTest {

//第一种方式,使用expected属性

@Test(expected=FileNotFoundException.class)

public void usingExpected() throws FileNotFoundException {

new FileInputStream("不存在的路径");

System.out.println("------测试中--------");

}

//第二种方式,使用try/catch和fial方法

@Test

public void usingCryCatchAndFail(){

try {

new FileInputStream("不存在的路径");

fail("前面的代码已经抛出FileNotFoundException异常");

} catch (FileNotFoundException e) {

assertTrue(e.getMessage().contains("不存在的文件路径"));

e.printStackTrace();

}

}

//第三种方式,使用expectedException规则

@Rule

public ExpectedException thrown=ExpectedException.none();

@Test

public void shouldTestExceptionMassage() throws FileNotFoundException{

thrown.expect(FileNotFoundException.class);

thrown.expectMessage("不存在的文件路径");

thrown.expectMessage("存在");

thrown.expectMessage("文件路径");

new FileInputStream("不存在的文件路径");

}

}


Junit 小案例 测试异常

原文:http://7883830.blog.51cto.com/7873830/1704618

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!