JUnit Exception Testing

前端 未结 5 537
广开言路
广开言路 2020-12-14 19:54

Edit: Not JUnit 4 available at this time.

Hi there,

I have a question about \"smart\" exception testing with JUnit. At this time, I do it like this:

5条回答
  •  难免孤独
    2020-12-14 20:33

    In Java 8, you can use lambda expressions to get tighter control over when the exception is thrown. If you use the annotations method then you're only asserting that the exception is thrown somewhere in the test method. If you're executing more than one line of code in the test then you risk your test passing when it should fail. Java 8 solution is something like this.

    static void  expectException(Class type, Runnable runnable) {
        try {
            runnable.run()
        } catch (Exception ex) {
            assertTrue(ex.getClass().equals(type));
            return;
        }
        assertTrue(false);
    }
    

    Usage:

    @Test
    public void test() 
        MyClass foo = new MyClass();
        // other setup code here ....
        expectException(MyException.class, () -> foo.bar());
    }
    

提交回复
热议问题