junit testing - assertEquals for exception

后端 未结 5 889

How can I use assertEquals to see if the exception message is correct? The test passes but I don\'t know if it hits the correct error or not.

The test I am running.

5条回答
  •  梦如初夏
    2021-02-08 16:55

    This is nice library that allows asserting exceptions in a clean way.

    Example:

    // given: an empty list
    List myList = new ArrayList();
    
    // when: we try to get the first element of the list
    when(myList).get(1);
    
    // then: we expect an IndexOutOfBoundsException
    then(caughtException())
            .isInstanceOf(IndexOutOfBoundsException.class)
            .hasMessage("Index: 1, Size: 0")
            .hasNoCause();
    

提交回复
热议问题