package com.laiwenhua.junitTest;java
import static org.junit.Assert.assertTrue;ide
import static org.junit.Assert.fail;測試
import java.io.FileInputStream;spa
import java.io.FileNotFoundException;get
import org.junit.Rule;it
import org.junit.Test;io
import org.junit.rules.ExpectedException;class
/**import
* 測試異常方法
* @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("不存在的文件路徑");
}
}