Junit 小案例 测试异常

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

}

}

相关文章
相关标签/搜索