1

I have the following method written that gets a substring from a string with the start and end index. For indexed that will go out of bounds, how do I write a test case in Junit? For example, if the string is banana and the method is run as getSubstring(3,12), the method will throw a out of bounds error. How do I write a test case that will pass when this error is shown?

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);
}
javabeginner
  • 91
  • 3
  • 11

1 Answers1

2

There are lots of ways to do this in JUnit, but the best way is to use the ExpectedException feature. You set up a @Rule that specifies that your test might throw an exception, and you can set expectations of what this exception will be - what type it will have, what message and so on.

At the top of your test class, you want something like

@Rule public ExpectedException exceptionRule = ExpectedException.none();

and then before the line of code which ought to throw the exception, you can write something like

exceptionRule.expect(MyException.class);

Then, your test will succeed if the right exception is thrown; but it will fail if it reaches the end without the exception being thrown.

See the Javadoc for more expectations that you can set up in ExpectedException rules.

Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110