Java 如何测试索引越界错误?

Java 如何测试索引越界错误?,java,string,testing,indexing,Java,String,Testing,Indexing,我编写了以下方法,该方法从具有开始和结束索引的字符串中获取子字符串。对于将超出范围的索引,如何在Junit中编写测试用例?例如,如果字符串是banana,并且该方法作为getSubstring(3,12)运行,则该方法将抛出越界错误。当显示此错误时,如何编写将通过的测试用例 public String getSubstring(int start, int end){ sub = MyString.str.substring(start, end); return

我编写了以下方法,该方法从具有开始和结束索引的字符串中获取子字符串。对于将超出范围的索引,如何在Junit中编写测试用例?例如,如果字符串是banana,并且该方法作为getSubstring(3,12)运行,则该方法将抛出越界错误。当显示此错误时,如何编写将通过的测试用例

public String getSubstring(int start, int end){
        sub = MyString.str.substring(start, end);
        return sub;
    }



@Test
public void testgetSubstring() {
    MyString test = new MyString();
    String result = test.getSubstring(3,12);
}

在JUnit中有很多方法可以做到这一点,但是最好的方法是使用
ExpectedException
特性。您设置了一个
@规则
,该规则指定您的测试可能会引发异常,并且您可以设置此异常的预期值—它将具有什么类型、什么消息等等

在你的测试课上,你想要

@Rule public ExpectedException exceptionRule = ExpectedException.none();
exceptionRule.expect(MyException.class);
然后在应该抛出异常的代码行之前,您可以编写如下代码

@Rule public ExpectedException exceptionRule = ExpectedException.none();
exceptionRule.expect(MyException.class);
然后,如果抛出正确的异常,测试将成功;但如果它在没有抛出异常的情况下到达终点,它将失败


有关可在
ExpectedException
规则中设置的更多期望,请参阅。

使用字符串长度函数