Junit4 : testing Exception

Junit 4.7 introduces the ExpectedException rule that eases Exception testing.

# the ‘yeah, kind of…’ way
I love Square’s projects. They are pushing great libs, especially on Android. They push a high level of quality on their code (unit testing, decoupling, readability & so…).

However, I was kind of surprised when I looked into the Phrase project, a single Class project that processes Android String formatting. Awesome project by the way.
The code is quite clean and the test cases seem well relevant, but testing Exception is like :

Ok. it does the job, but the readability could clearly be improved as there are some uncessary extra code here. Adding try/catch blocks into Unit tests is simply not the way to do AMHA. These tests could be enhanced 🙂

# the partial way
You can use the expected parameter within the @Test annotation to specify the expected Throwable. The code is clearly more readable than previously:

@Test(expected = IllegalArgumentException.class)
  public void loneCurlyBraceIsAMistake() {
      from("hi { {age}.");
  }

However, this way has its limit, this is why it is ‘partial’. Consider this test :

In this precise test case, you don’t know if the Constructor throws the Exception or the following method. You could (and should) of course split the test but let’s see some better way.

# a better way
As briefly evoked in the introduction, Junit 4.7 introduces the ExpectedException rule. The power of this rule lies 1. in covering the previously explained limitation, 2. in gaining in readability and 3. in the ability to not only handle the Exception type, but also the Exception message.
Consider the Square/Phrase test updated with ExpectedException :

As you can see, the test is clearly more consize and more readable. You only need to declare the ExpectedException rule in your test class as public. That’s it 🙂

I have submited a pull request to Square/Phrase project by correcting all the Unit Tests dealing with Exceptions so the quality and readability of the code will hopefully benefit to the community.

To sum up ‘Testing Exception’ :
– avoid try/catch blocks within your unit tests
– push readability as much as possible
– use ExpectedException rule to test the Throwable and the associated message

Laisser un commentaire

Votre adresse de messagerie ne sera pas publiée. Les champs obligatoires sont indiqués avec *