JUnit: Possible to 'expect' a wrapped exception?

后端 未结 7 1859
花落未央
花落未央 2020-12-05 12:43

I know that one can define an \'expected\' exception in JUnit, doing:

@Test(expect=MyException.class)
public void someMethod() { ... }
         


        
7条回答
  •  庸人自扰
    2020-12-05 13:15

    I wrote a little JUnit extension for that purpose. A static helper function takes a function body and an array of expected exceptions:

    import static org.junit.Assert.assertTrue;
    import static org.junit.Assert.fail;
    
    import java.util.Arrays;
    
    public class AssertExt {
        public static interface Runnable {
            void run() throws Exception;
        }
    
        public static void assertExpectedExceptionCause( Runnable runnable, @SuppressWarnings("unchecked") Class[] expectedExceptions ) {
            boolean thrown = false;
            try {
                runnable.run();
            } catch( Throwable throwable ) {
                final Throwable cause = throwable.getCause();
                if( null != cause ) {
                    assertTrue( Arrays.asList( expectedExceptions ).contains( cause.getClass() ) );
                    thrown = true;
                }
            }
            if( !thrown ) {
                fail( "Expected exception not thrown or thrown exception had no cause!" );
            }
        }
    }
    

    You can now check for expected nested exceptions like so:

    import static AssertExt.assertExpectedExceptionCause;
    
    import org.junit.Test;
    
    public class TestExample {
        @Test
        public void testExpectedExceptionCauses() {
            assertExpectedExceptionCause( new AssertExt.Runnable(){
                public void run() throws Exception {
                    throw new Exception( new NullPointerException() );
                }
            }, new Class[]{ NullPointerException.class } );
        }
    }
    

    This saves you writing the same boiler plate code again and again.

提交回复
热议问题