In Java how can I validate a thrown exception with JUnit?

前端 未结 10 1190
甜味超标
甜味超标 2020-11-30 05:47

When writing unit tests for a Java API there may be circumstances where you want to perform more detailed validation of an exception. I.e. more than is offered by the @t

10条回答
  •  执念已碎
    2020-11-30 06:10

    Looking at the proposed answers, you can really feel the pain of not having closures in Java. IMHO, the most readable solution is ye good old try catch.

    @Test
    public void test() {
        ...
        ...
        try {
            ...
            fail("No exception caught :(");
        }
        catch (RuntimeException ex) {
            assertEquals(Whatever.class, ex.getCause().getClass());
            assertEquals("Message", ex.getMessage());
        }
    }
    

提交回复
热议问题