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("不存在的文件路径");
}
}