junit testing - assertEquals for exception

后端 未结 5 891

How can I use assertEquals to see if the exception message is correct? The test passes but I don\'t know if it hits the correct error or not.

The test I am running.

5条回答
  •  死守一世寂寞
    2021-02-08 16:46

    Java 8 solution

    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!" );
    }
    

    Also, if you would like to read some reasons why you should not want to assertTrue that the message of your exception is equal to a particular value, see this: https://softwareengineering.stackexchange.com/a/278958/41811

提交回复
热议问题