首页 技术 正文
技术 2022年11月10日
0 收藏 975 点赞 2,143 浏览 1498 个字

1.异常测试

对可能抛出的异常进行测试:

  • 异常本身是方法签名的一部分:

    * public static int parseInt(String s) throws NumberFormatException

  • 测试错误的输入是否导致特定的异常:

    * Integer.parseInt(null)

    * Integer.parseInt("")

    * Integer.parseInt("xyz")

2.异常测试的方法:

  • 使用try..catch (Exception e)捕获异常,但这样会编写许多try..catch代码
  • expected测试异常,推荐

2.1示例1

package com.testList;import org.junit.*;import static org.junit.Assert.fail;public class SequenceTest {
//使用try...catch
@Test
public void test1() throws Exception{
try {
Integer.parseInt(null);
fail("should throw java.lang.NumberFormatException");
}catch (NumberFormatException e){
System.out.println("pass");
}
}
//使用expected捕获异常
@Test(expected = NumberFormatException.class)
public void test2() throws Exception{
Integer.parseInt("p");
}
}

廖雪峰Java8JUnit单元测试-2使用JUnit-2异常测试
### 2.2示例2
Calculator.java
“`#java
package com.testList;

public class Calculator {

public int calculator(String expression){

if (expression == null){

throw new NumberFormatException();

}

String[] ss = expression.split("\+");

int sum = 0;

for(String s:ss){

sum = sum + Integer.parseInt(s.trim());

}

return sum;

}

}

CalculatorTest.java
```#java
package com.testList;import org.junit.After;
import org.junit.Before;
import org.junit.Test;import java.util.Calendar;import static org.junit.Assert.*;public class CalculatorTest {
Calculator calc;
@Before
public void setUp(){
calc = new Calculator();
}
@Test(expected = NumberFormatException.class)
public void testCalcWithEmptyString(){
int r = calc.calculator("");
}
@Test(expected =NumberFormatException.class)
public void testCalcAdd3Numbers(){
int r = calc.calculator(null);
}
@After
public void tearDown(){
calc = null;
}
}

廖雪峰Java8JUnit单元测试-2使用JUnit-2异常测试

3.总结

  • 测试异常可以使用@Test(expected = Exception.class)
  • 对可能发生的每种类型的异常进行测试
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,093
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,569
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,417
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,190
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,825
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,908