Testing Custom Exception Handling Classes in Spring MVC

You can view this as a supplement to the post I wrote a couple of months ago titled Testing for 404 and Custom Exceptions in Spring MVC. In that post we talked about configuring our tests to use our custom Exception Handler classes which we put in play with Spring's @ExceptionHandler annotation.

Our goal for today is to test that the custom UnknownResourceException class we created is indeed being called to resolve application 404s.

The earlier post lays the groundwork on our 404 test, like how we added an ExceptionResolver in our test class @Before setUp() method and used it to build mockMvc.

mockMvc = MockMvcBuilders.standaloneSetup(mockController)

With our exception resolver in place the 404 test is straightforward and the board is green.

But back to the main point. How do we confirm that our custom UnknownResourceException was called and made the magic happen behind the scenes?

First let's look at the output of the mockMvc get request with attention to the Resolved Exception. We see that our custom UnknownResourceException stepped up and did the job. That's cool, but how do we confirm that in a test?

First we're going to pipe our mockMvc request into an MvcResult object and use a Hamcrest matcher on the result.

MvcResult result = mockMvc.perform(get("/badurl"))

We could perform a Junit assert with a class.isAssignableFrom() function, but the Hamcrest match is cleaner.

The source code in this post is available in the v0.1.9 branch of NixMash Spring on GitHub.

More Like This Post