Vallado

A library that supports exception testing with Java 8 Lambdas. Can be used with JUnit and TestNG.

Get Vallado

I strongly recommend to use Fishbowl instead of Vallado, because it makes it possible to use the AAA (Arrange-Act-Assert) pattern for writing tests for code that throws an exception.

An example is worth a thousand words.

when(() -> throw new RuntimeException())
  .thenA(RuntimeException.class)
  .isThrown();

How to use Vallado

1. Import the when method.

import static org.junit.contrib.java.lang.throwable.When.when;

2. Enclose the code that throws the exception with when.

when(() -> { /* code that throws an exception */ })

3. Specify the exception's type.

when(  )
  .thenA(FooBarException.class)

4. Optionally specify further assertions for the exception by using Hamcrest matchers.

when(  )
  .thenA(  )
  .that(hasProperty("message", startsWith("A")))
  .and(hasProperty("message", contains("foo bar")))

5. Execute the code and verify that the specified exception is thrown.

when(  )
  .thenA(  )
  
  .isThrown();

Use Vallado with older version of Java

You can use Vallado with an older version of Java, too. Therefore you have to creates Statement objects.

when(new Statement() {
  public void evaluate() {
    throw new RuntimeException();
  }
})
  .thenA(RuntimeException.class)
  .isThrown();

Alternatives

Fishbowl makes it possible to use the AAA (Arrange-Act-Assert) pattern for writing tests for code that throws an exception. The following snippet is the example from above but written with Fishbowl and Hamcrest

Throwable exception = exceptionThrownBy(() -> throw new RuntimeException());
assertThat(exception, is(instanceOf(RuntimeException.class)));

Rafał Borowiec wrote the Blog article JUnit: testing exception with Java 8 and Lambda Expressions, where he describes a similar approach to test exception handling. His equivalent to the example from above is

assertThrown(() -> throw new RuntimeException())
  .isInstanceOf(RuntimeException.class);