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:

@Test(expected=InsufficientFundsException.class) ...

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

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.