java - Comment affirmez-vous qu'une certaine exception est lancée dans les tests JUnit 4

Mots clés : javaexceptionjunitjunit4assertjava

meilleur 5 Réponses java - Comment affirmez-vous qu'une certaine exception est lancée dans les tests JUnit 4

vote vote

96

@Test(expected = IndexOutOfBoundsException.class) public void testIndexOutOfBoundsException() {      ArrayList emptyList = new ArrayList();     Object o = emptyList.get(0);  } 
vote vote

89

public class FooTest {   @Rule   public final ExpectedException exception = ExpectedException.none();    @Test   public void doStuffThrowsIndexOutOfBoundsException() {     Foo foo = new Foo();      exception.expect(IndexOutOfBoundsException.class);     foo.doStuff();   } } 
vote vote

80

try {     methodThatShouldThrow();     fail( "My method didn't throw when I expected it to" ); } catch (MyException expectedException) { } 
vote vote

64

@Test public void verifiesTypeAndMessage() {     assertThrown(new DummyService()::someMethod)             .isInstanceOf(RuntimeException.class)             .hasMessage("Runtime exception occurred")             .hasMessageStartingWith("Runtime")             .hasMessageEndingWith("occurred")             .hasMessageContaining("exception")             .hasNoCause(); } 
vote vote

59

@Test public void testFooThrowsIndexOutOfBoundsException() {     Throwable exception = assertThrows(IndexOutOfBoundsException.class, () -> foo.doStuff());     assertEquals("expected messages", exception.getMessage()); } 
@Test(expected = IndexOutOfBoundsException.class) public void testFooThrowsIndexOutOfBoundsException() {     foo.doStuff(); } 
public class XxxTest {     @Rule     public ExpectedException thrown = ExpectedException.none();      @Test     public void testFooThrowsIndexOutOfBoundsException() {         thrown.expect(IndexOutOfBoundsException.class)         //you can test the exception message like         thrown.expectMessage("expected messages");         foo.doStuff();     } } 
@Test public void testFooThrowsIndexOutOfBoundsException() {     try {         foo.doStuff();         fail("expected exception was not occured.");     } catch(IndexOutOfBoundsException e) {         //if execution reaches here,          //it indicates this exception was occured.         //so we need not handle it.     } } 

Questions similaires