JUnit right way of test expected exceptions

后端 未结 4 1096
走了就别回头了
走了就别回头了 2020-12-15 20:37

Hello guys I was wondering if this way of testing my exception is ok, i have this exception i need to throw in the second test annotation, im receiving as result a red evil

4条回答
  •  猫巷女王i
    2020-12-15 21:06

    if your are using java 8, I would recommend to go for the AssertJ library

    public void GTFRICreationTester_shouldFail()  {
        assertThatExceptionOfType(EXCEPTION_CLASS).isThrownBy(() -> { factory.createLocomotive(weirdProtocol, false, new Date()) })
                                                   .withMessage("MESSAGE")
                                                   .withMessageContaining("MESSAGE_CONTAINING")
                                                   .withNoCause();         
    
        }
    

    with that solution you can at one verify exception type, with message etc.

    for more reading, take a look at: http://joel-costigliola.github.io/assertj/assertj-core-features-highlight.html#exception-assertion

提交回复
热议问题