Testing for Expected Exceptions in JUnit 5: Quite an Improvement
There are a few different ways to test that a constructor or other unit in a Java program throws a certain exception. JUnit 5 introduced a new way of testing for expected exceptions, which is an improvement from what was available for the purpose in previous versions.
Maybe with JUnit 4 you preferred the good old-fashioned Try-Catch with fail()
. I did, too. That has its drawbacks, as I will show in a little bit. I think you’ll like assertThrows()
in JUnit 5 a lot better.
I like to use concrete examples for these articles. Let’s say we’re working on a bank account program. If we don’t use a third party library like Joda Money, we’ll have to create our own class to represent money amounts. Let’s not use double
to represent money amounts, that’s a rookie mistake.
And maybe BigDecimal
looks like an attractive option for when we have to convert strong currencies like the euro to weak currencies like the Iranian rial (one euro will get you almost fifty thousand rial), BigDecimal
still doesn’t carry information specific to currency, like that “€” is the symbol for euros.
The one flaw all objects of any class have in common, whether it’s Money
in Joda Money, BigDecimal
from the JDK or our own CurrencyAmount
, is the always present risk of the dreaded…