Asserting exceptions
One area where unit tests excel is in testing error handling code. As an example of testing exception throwing, let’s add a business requirement that our usernames must be at least four characters long. We think about the design we want and decide to throw a custom exception if the name is too short. We decide to represent this custom exception as class InvalidNameException
. Here’s what the test looks like, using AssertJ:
@Test public void rejectsShortName() { assertThatExceptionOfType(InvalidNameException.class) .isThrownBy(()->new Username("Abc")); }
We can consider adding another test specifically aimed at proving that a name of four characters is accepted and no exception is thrown:
@Test public void acceptsMinimumLengthName() { assertThatNoException() ...