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)?