Three Schools for Expecting Exceptions

In addition to ensuring that the happy path through our code works, we want to verify that exceptions get thrown when expected. Understanding the conditions that cause a class to throw exceptions can make life a lot easier for a client developer using the class.

JUnit supports at least three different ways of specifying that you expect an exception to be thrown. Let’s examine a simple case: ensure that Account code throws an Exception when a client attempts to withdraw more than the available balance.

Simple School: Using an Annotation

The JUnit @Test annotation supports passing an argument that specifies the type of an expected exception:

iloveyouboss/13/test/scratch/AssertTest.java
 
@Test(expected=InsufficientFundsException.class) ...

Get Pragmatic Unit Testing in Java 8 with JUnit now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.