一、 测试异常
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),我们将立即处理。