For JUnit 4 you can use this:
@Test(expected = IndexOutOfBoundsException.class)
public void testIndexOutOfBoundsException()
{
ArrayList emptyList = new ArrayList();
Object o = emptyList.get(0);
}
You can click here to know more.
As we know that JUnit5 has released, you can use Assertions.assertThrows():
@Test public void testFooThrowsIndexOutOfBoundsException()
{
Throwable exception = assertThrows(IndexOutOfBoundsException.class, () -> foo.doStuff());
assertEquals("expected messages", exception.getMessage());
}
It's not advised to use @Test(expected=IndexOutOfBoundsException.class) as the test will fail if IndexOutOfBoundsException is thrown before foo.doStuff()
To solve this error use this syntax:
mTextView.setText("Response is: "+
((response.length()>499) ? response.substring(0,500));