How do I assert my exception message with JUnit Test annotation?

前端 未结 12 2010
广开言路
广开言路 2020-12-12 08:53

I have written a few JUnit tests with @Test annotation. If my test method throws a checked exception and if I want to assert the message along with the exceptio

12条回答
  •  轮回少年
    2020-12-12 09:05

    Import the catch-exception library, and use that. It's much cleaner than the ExpectedException rule or a try-catch.

    Example form their docs:

    import static com.googlecode.catchexception.CatchException.*;
    import static com.googlecode.catchexception.apis.CatchExceptionHamcrestMatchers.*;
    
    // given: an empty list
    List myList = new ArrayList();
    
    // when: we try to get the first element of the list
    catchException(myList).get(1);
    
    // then: we expect an IndexOutOfBoundsException with message "Index: 1, Size: 0"
    assertThat(caughtException(),
      allOf(
        instanceOf(IndexOutOfBoundsException.class),
        hasMessage("Index: 1, Size: 0"),
        hasNoCause()
      )
    );
    

提交回复
热议问题