Search code examples
javaunit-testingjunit4spring-boot-testassertj

Get Exception object in Unit Test with Spring Boot Starter Test


In my program I'm throwing a custom Exception object MyCustomException, which looks like this:

public class MyCustomException
{
    private MyCustomExceptionObject myCustomExceptionObject;
    // Getters, Setters, Constructors...
}

public class MyCustomExceptionObject
{
    int code;
    // Getters, Setters, Constructors...
}

With Spring Boot Starter Test I've got many testing libraries at my disposal.

  • AssertJ
  • JUnit4
  • Mockito
  • Hamcrest

Currently I'm mainly using AssertJ. One of my tests give invalid parameters to a method and expect an exception.

@Test
public void test()
{
    org.assertj.core.api.Assertions.assertThatThrownBy(() -> someMethod(-1)).isExactlyInstanceOf(MyCustomException.class);
}

public void someMethod(int number)
{
    if (number < 0)
    {
        throw new MyCustomException(new MyCustomExceptionObject(12345));
    }
    //else do something useful
}

This works fine, but I want to test the exceptions more specifically, testing if the code is as expected. Something like this would work:

try
{
    someMethod(-1);
}
catch (MyCustomException e)
{
    if (e.getCode() == 12345)
    {
        return;
    }
}

org.assertj.core.api.Assertions.fail("Exception not thrown");

but I'm rather looking for a one-liner like:

org.assertj.core.api.Assertions.assertThatThrownBy(() -> someMethod(-1)).isExactlyInstanceOf(MyCustomException.class).exceptionIs((e) -> e.getCode() == 12345);

Does something like this exist in any of the above listed testing libraries (AssertJ preferred)?


Solution

  • I would give a try to catchThrowableOfType which allows you to assert your custom exception data, for exanple:

    class CustomParseException extends Exception {
       int line;
       int column;
    
       public CustomParseException(String msg, int l, int c) {
         super(msg);
         line = l;
         column = c;
       }
     }
    
     CustomParseException e = catchThrowableOfType(
                                () -> { throw new CustomParseException("boom!", 1, 5); }, 
                                CustomParseException.class);
     // assertions succeed
     assertThat(e).hasMessageContaining("boom");
     assertThat(e.line).isEqualTo(1);
     assertThat(e.column).isEqualTo(5);