【发布时间】:2016-04-16 12:07:43
【问题描述】:
我需要创建一个接受字符串作为值并满足以下要求的整数列表:
添加的值必须是数字的字符串表示形式。该列表应抛出带有自定义消息的自定义异常,以防万一: * 添加的值为 null 或为空 * 添加的值不是数字的字符串表示 * 我们尝试从列表中读取的索引超出范围
我还有一些单元测试来检查我是否正确处理了异常。
这是 CustomException 类:
public class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
public CustomException() {
}
public CustomException expect(NumberFormatException e) {
return new CustomException("Not a number");
}
public CustomException expect(NullPointerException e) {
return new CustomException("Null");
}
public CustomException expect(IndexOutOfBoundsException e) {
return new CustomException("Index out of bounds");
}
}
这里是单元测试:
public class MyListTest {
private List<String> list;
private Class<CustomException> exceptionType = CustomException.class;
private String[] initData = {"12", "23", "34", "45"};
@Rule
public ExpectedException exception = ExpectedException.none();
@Before
public void setUp() {
this.list = new StringList();
}
@Test
public void testAddValuesToTheList() {
initData();
assertEquals(initData.length, list.size());
for (String data : initData) {
assertTrue(list.contains(data));
}
}
private void initData() {
for (String numberAsString : initData) {
list.add(numberAsString);
}
}
@Test
public void testAddNonIntegerValue() {
exception.expect(exceptionType);
exception.expectMessage("Invalid number.");
list.add("Hey, I'm not an integer.");
}
@Test
public void testAddNonNullValue() {
exception.expect(exceptionType);
exception.expectMessage("Null");
list.add(null);
}
@Test
public void testIndexOutOfBounds() {
initData();
exception.expect(exceptionType);
exception.expectMessage("Index out of bounds.");
list.get(initData.length);
}
}
所以我的问题是:如何使用自定义异常类来检查上面对我的列表的要求?
【问题讨论】:
-
你有什么问题?
-
目前还不清楚答案是什么。你刚才说了你的要求……
标签: java unit-testing exception-handling