O'Reilly logo

Pragmatic Unit Testing in Java 8 with JUnit by Jeff Langr, Andy Hunt, Dave Thomas

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required