Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (10.2k points)

How can I use JUnit4 idiomatically to test that some code throws an exception?

While I can certainly do something like this:

@Test public void testFooThrowsIndexOutOfBoundsException()

{

boolean thrown = false; try { foo.doStuff();

}

catch (IndexOutOfBoundsException e) {

thrown = true; }

assertTrue(thrown); }

I recall that there is an annotation or an Assert.xyz or something that is far less kludgy and far more in-the-spirit of JUnit for these sorts of situations.

1 Answer

0 votes
by (46k points)

 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)); 

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...