How do you assert that a certain exception is thrown in JUnit 4 tests?

前端 未结 30 2000
忘掉有多难
忘掉有多难 2020-11-21 22:23

How can I use JUnit4 idiomatically to test that some code throws an exception?

While I can certainly do something like this:

@Test
public void testFo         


        
30条回答
  •  面向向阳花
    2020-11-21 23:02

    Java 8 solution

    If you would like a solution which:

    • Utilizes Java 8 lambdas
    • Does not depend on any JUnit magic
    • Allows you to check for multiple exceptions within a single test method
    • Checks for an exception being thrown by a specific set of lines within your test method instead of any unknown line in the entire test method
    • Yields the actual exception object that was thrown so that you can further examine it

    Here is a utility function that I wrote:

    public final  T expectException( Class exceptionClass, Runnable runnable )
    {
        try
        {
            runnable.run();
        }
        catch( Throwable throwable )
        {
            if( throwable instanceof AssertionError && throwable.getCause() != null )
                throwable = throwable.getCause(); //allows "assert x != null : new IllegalArgumentException();"
            assert exceptionClass.isInstance( throwable ) : throwable; //exception of the wrong kind was thrown.
            assert throwable.getClass() == exceptionClass : throwable; //exception thrown was a subclass, but not the exact class, expected.
            @SuppressWarnings( "unchecked" )
            T result = (T)throwable;
            return result;
        }
        assert false; //expected exception was not thrown.
        return null; //to keep the compiler happy.
    }
    

    (taken from my blog)

    Use it as follows:

    @Test
    public void testThrows()
    {
        RuntimeException e = expectException( RuntimeException.class, () -> 
            {
                throw new RuntimeException( "fail!" );
            } );
        assert e.getMessage().equals( "fail!" );
    }
    

提交回复
热议问题