Proposal for Assert.assertException

"Johannes [email protected] [junit]" <[email protected]> Tue, 19 May 2015 07:06:08 +0200
Newsgroups gmane.comp.java.junit.user
Message-ID <[email protected]>
Hello,

I always found testing thrown exceptions tedious, since it required a 
new test method for every exception that shall be thrown.
Since the introduction of Java 8 lambda expressions I found this new 
idiom to be quite useful:

     @Test
     public void testIndexOutOfBoundsIsThrown() {
         List<Object> l = new ArrayList<>();
         assertException(() -> l.add(-1, new Object()));
         assertException(() -> l.add(1, new Object()), 
IndexOutOfBoundsException.class);
     }

Here is the code for the assertions:

     public static void assertException(Runnable r) {
         assertException(r, Exception.class);
     }

     public static void assertException(Runnable r, Class<? extends 
Exception> exceptionClass) {
         try {
             r.run();
             fail("expected " + exceptionClass.getName());
         } catch (Exception e) {
             Assert.assertTrue("expected " + exceptionClass + " but was 
" + e,
                     exceptionClass.isAssignableFrom(e.getClass()));
         }
     }

What do you think?
If you like the idea, I can create a pull request on github.

Johannes


------------------------------------
Posted by: Johannes <[email protected]>
------------------------------------