文字列を値として受け入れ、次の要件を満たす整数リストを作成する必要があります。カスタムメッセージを含むリストのカスタム例外ハンドラを作成するにはどうすればよいですか?
追加された値は文字列表現でなければなりません。リストには、カスタムメッセージ付きのカスタム例外がスローされるはずです。 *追加された値がnullまたは空です *追加された値は数値の文字列ではありません *リストから読み込もうとしているインデックスが不足していますbound
私は例外を適切に処理したかどうかをチェックするユニットテストもあります。
これは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);
}
}
だから私の質問は次のとおりです。要件をチェックするために、カスタム例外クラスを使用する方法私のリストの上から?
どういうところですか? –
答えが何であるかは不明です。あなたはちょうどあなたの要求を言った... – dambros