Testing a Spring MVC Search Form

Version 0.1.4 of NixMash Spring on GitHub contains the Contact Search Form shown below. Here we'll look at the Controller source and its supporting tests.

The Contact Controller MVC Method

First the Contact Controller /search source where we see the four possible results of searching contacts by last name.

1) Empty form, nothing entered. Redirect to /contacts and display all contacts.

2) No contacts found. Create rejectValue BindingResult error on the lastName field, passing the last name entered to the message search.contact.notfound property. Display “not found” by default.

3) Multiple Contacts are found. Display Contact List View with the contacts retrieved.

4) A Single Contact is found. Create a Contact Model Attribute and redirect to the Contact View page, passing the contact's Id as a path parameter.

The Tests

Before testing the four possible outcomes of the search form we need to configure our Mock MVC Controller viewer with setSingleView() on the MockMvc builder. This is so the mock framework won’t try to resolve the view name coming from the controller on its own.

There's something else here to mention. We're using a “new ContactController(contactService)” as opposed to a controller with a mockService. Since the application is using Spring Profiles (H2 for tests, MySQL for everything else) we can populate Lists and Contact objects straight from the test H2 ContactService saving time and coding to populate a bunch of mock objects.

1) Form is empty, all contacts displayed. The main points here are the view name of “redirect:/contacts/” and that all contacts all displayed. (allContacts is created in the @Before test processes, returning all contacts from our H2 ContactService.)

2) No Contacts are found. Return an error message. Here we use attributeHasFieldErrorCode to test that the lastName field of the contact model generates the search.contact.notfound error. We could have done a model().hasErrors() as an alternative.

3) Multiple Contacts are found. Display Contact List View. Our main concern here is that the contacts Model Attribute was created and we display those with the “list” view.

4) A Single Contact is found. Redirect to the Contact View page, passing the ContactId as a parameter. The thing to notice here is that like #1 tests for displaying all contacts, we're not testing for a redirectUrl() but rather a “redirect” in the view name, “redirect:/contact/1.”

All of the code referred to in this post can be found in my NixMash Spring app on GitHub in the v0.1.4 branch.

More Like This Post