JUnit rules – executing additional verification when exceptions are thrown

In this post I will show you quickly how handy JUnit rules are if you need to solve the following challenge

A method catches an exception and has to perform some extra tasks before rethrowing or throwing a wrapper exception.
Calls to the extra tasks and the thrown exception should be verified by a unit test.

This means you have some code like this

And call in this line

needs to be verified as well as the thrown exception.

Straight forward … but ugly

I will not go into details of this variant

as I personally try to avoid try catch constructs in my test code if feasible.

The easy one first

Verifying that the exception is thrown is fairly easy, JUnit provides to potential options here

  1. The expected parameter of the @Test annotation and
  2. a rule called ExceptionRule

The first option will look like this

the second one like this

No it’s getting a little bit more complicated

The problem behind the mentioned requirement for testing is the following

All the verify( … ) steps you do, after executing your method under test, will not be executed as the exception stops the rest of the test method execution as usual if exceptions are thrown and not caught.

JUnit rules for the rescue

With JUnit rules, we can easily create a way to provide additional verification steps even in case of exceptions thrown.

I’m aware that JUnit provides already a verifier rule, but I will not use it. This class has the drawback that the verification logic is burned into it, when it’s setup.

So what we need is a rule that allows us to specify per test an additional verification logic which is applied after the test is executed.

The general usage should look like this

To get this up and running we need to things

  • the VerifyRule
  • any kind of callback interface that can be set on the verify rule

Let’s start with the callback interface

Nothing special here, as you can see.

Now let’s focus on the VerifyRule

As you can see it implements the TestRule interface and provides a method to set the VerifyRuleCallback. The callback is then used within the evaluate method of the VerifyRuleStatement that needs to be implemented to run our own callback evaluation.

Tying it all together

With the new rule and the callback a test could look like this

Summary

As we have seen JUnit rules provide a very nice and easy way to create clean and understandable test code when, and not only in this case, these kind of requirements on testing came up,

 
3 Kudos
Don't
move!

Leave a Reply

Your email address will not be published. Required fields are marked *