In my first post on asserting exceptions with JUint, I showed how to test that a specific type of exception is thrown with expected substrings in the error message. In my second post, I showed how we can write a custom [Matcher] to inspect the contents of the exception. In this post, I’ll show you how to take advantage of the stock IsEqual matcher to accomplish the same task, but with less work.
This Matcher is straightforward - it evaluates whether two objects are equal by calling equals(Object) on one of the objects that isn’t null, passing in the other. So, to use it with our custom exception, we’ll need to make sure that our equals(Object) method correctly evaluates two of its instances.
The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).
This won’t help us here, because we’ll be comparing exceptions thrown in our code with one we instantiated in our unit test. We’re going to have to implement equals(Object) ourselves.
Here’s my simple custom exception:
You have to be careful when implementing either equals(Object) or hashCode(). The rule is that if you implement either of these methods, then you need to implement both. Two objects that are equal must have the same hash code. If they don’t, and you try to add two distinct, but equal instances of a class to a Map, they’d both be accepted. This is because internally, the Map stores the items in ‘buckets’ based on their hash codes, and then only has to check equality within a bucket. If two objects have different hash codes, then they won’t be compared to each other.
Your IDE should have the ability to generate what we need here. If you’re using Eclipse (I recommend the STS version, right-click in the source file, select “Source”, and the select “Generate hashCode() and equals()”.
After selecting that option, choose which private members will be used in the two methods. I recommend selecting “‘Use blocks in ‘if’ statements” in order to help wrong code look wrong, should someone modify these methods down the road.
Here’s our final ErrorCodeException class with the newly generated code:
Verifying _equals(Object) and hashCode()
Even though we generated this code, we still need to test it. Here’s the test fixture for ErrorCodeException:
Using the IsEqual Matcher In Our Unit Tests
Now that we’ve implemented equals(Object) and hashCode() for our custom exception, we can use the IsEqual Matcher to setup an expectation for a specific exception.
In the first test, I create an IsEqual Matcher with the exception that I want to compare the thrown exception to. No custom Matcher was required, and my custom exception is now more useful because of it.
In my second test, I include the ‘old way’ of checking exceptions to demonstrate how much easier and more readable exception tests are when using JUnit’s Rules feature.
In my previous post, I demonstrated how to use JUnit’sRules feature to assert expected assertions in your unit tests. In this post, I’ll show you how to write custom Matchers that will help give you more power when inspecting your exceptions.
This demo uses the following Maven dependencies:
We’ll start with a custom exception which does little more than remember the error code at the time the exception was thrown.
Our Exception Matcher
When we pass our Matcher to JUnit’s ExpectedException instance, we’re given a chance to match the exception itself, not the message. In this case, we’re going to write a Matcher that makes sure that the exception’s error code was as expected. We can only match on an instance of our _ ErrorCodeException_, so we’ll save some effort and extend TypeSafeMatcher.
TypeSafeMatcher : Convenient base class for Matchers that require a non-null value of a specific type. This simply implements the null check, checks the type and then casts.
Example Tests With ExpectedException and Our Custom Matcher
With the components in place, let’s start testing. Of course, if you only have one or two error test cases, then a custom Matcher might take more work than it saves, but you end up with code that any developer should be able to read, which might reduce maintenance costs.
Asserting Exceptions The Old Way
To demonstrate the benefits of using custom Matchers with JUnit’s ExcpectedException, here are the alternatives that you’re probably familiar with, with inline comments explaining why they’re not ideal.
If you’re not familiar with JUnit’s @Rule feature for asserting exceptions in your tests, then read on - you’re about to start using it.
Assert Exception Type
It’s very simple to assert that a given type of exception is thrown in a JUnit test case with the following:
Assert Exception Message (The Old Way)
But, what if you want to be more specific, and check the message itself? I’ve always done the following:
Heres’s another variant you’re probably familiar with:
Assert Exception Message With JUnit Rules
The above methods always felt like hacks. I recently came across JUnit’s @Rule feature, which saves tons of code and is much easier to read. You first define your public ExpectedException instance, and give it a @Rule annotation. Then, in each test case that wants to use it, you set what type of exception you’re expecting, and optionally a substring to look for in the exception message:
Since expectMessage is looking for substrings, you can use several of them to test more complicated exception messages:
More Advanced: Custom Matchers
In my next post, I’ll i describe how to implement a custom Matcher for more complicated Exception assertions.
Ideally, your unit test suites require no external dependencies - those should be mocked out. However, sometimes you want extra assurance that your code works with live endpoints via integration tests.
For example, you might want to make sure that your code can successfully navigate your corporate proxy and firewall to make external web requests. For this, we’ll write tests that only run when a command line parameter is defined.
I’ve been working with Hibernate for several years now, yet I learn something new about it all the time. The more time I spend with the framework, the more concerned I am about how it will be used by developers new to it.
The simplicity of the entrance into the world of O/R mapping however gives a wrong impression of the complexity of these frameworks. Working with more complex applications you soon realize that you should know the details of framework implementation to be able to use them in the best possible way. In this article, we describe some common anti-patterns which may easily lead to performance problems.
The law of leaky abstractions means that whenever somebody comes up with a wizzy new code-generation tool that is supposed to make us all ever-so-efficient, you hear a lot of people saying “learn how to do it manually first, then use the wizzy tool to save time.” Code generation tools which pretend to abstract out something, like all abstractions, leak, and the only way to deal with the leaks competently is to learn about how the abstractions work and what they are abstracting. So the abstractions save us time working, but they don’t save us time learning.
Don’t stop learning about a framework once you figure out how to use it - that’s only the beginning.