Monday, September 7, 2009

Testing SimpleFormController with Spring MVC

In this article, I will show how one can develop “test-first” using Spring-webMVC and spring-test. I therefore assume you know the basics of spring-mvc. My example will be around some Person management system. First, assume we have a Person object :


  1. public class Person {
  2. private Long id;
  3. private String firstName;
  4. private String lastName;
  5. public Person(String firstName, String lastName) {
  6. this.firstName = firstName;
  7. this.lastName = lastName;
  8. }
  9. public Long getId() {
  10. return id;
  11. }
  12. private void setId(Long id) {
  13. this.id = id;
  14. }
  15. public String getFirstName() {
  16. return firstName;
  17. }
  18. public void setFirstName(String firstName) {
  19. this.firstName = firstName;
  20. }
  21. public String getLastName() {
  22. return lastName;
  23. }
  24. public void setLastName(String lastName) {
  25. this.lastName = lastName;
  26. }
  27. }

And a service interface allowing basic CRUD operations for a person :


  1. public interface PersonService {
  2. public List read(Person p);
  3. public void save(Person p);
  4. public void delete(Person p);
  5. }

We want a web interface that allow the user to save a new Person or to modify an existing person. For this I’ll use a SimpleFormController. It will be responsible for presenting the form, calling the person’s service save(Person), and forwarding the user to a success page (when the person has correctly been saved).


This controller will be configured in a context file like this :


  1. <beans xmlns="http://www.springframework.org/schema/beans"
  2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://www.springframework.org/schema/beans
  4. http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
  5. <bean name="/editPerson" class="myProject.web.EditPersonController">
  6. <property name="commandClass" value="myProject.Person"/>
  7. <property name="formView" value="personForm"/>
  8. <property name="successView" value="personSaved"/>
  9. </bean>
  10. </beans>

To have our test being able to load a context, we’ll use the jUnit’s @RunWith annotation, and to make our test load our specific context we’ll use the Spring’s @ContextConfiguration annotation. For more details on Spring’s test API, see the chapter 13 of the Spring framework documentation.


  1. @RunWith(SpringJUnit4ClassRunner.class)
  2. @ContextConfiguration(locations={"/myProject/EditPersonControllerTest-context.xml"})
  3. public class EditPersonControllerTest {
  4. <strong>@Autowired</strong>
  5. <strong>EditPersonController controller;</strong>
  6. /**
  7. * Tests the creation of a new Person.
  8. **/
  9. @Test
  10. public void testCreate() {
  11. }
  12. }

The @Autowired annotation will do “by-type” bean injection. This means that since our context contains a single bean of type myProject.web.EditPersonController, that bean (the one we named “/editPerson”) will be injected in field “controller” at runtime, before the test methods are called. But for now, the test just doesn’t compile because we haven’t created the EditPersonController class. Let’s create this controller :


  1. import org.springframework.web.servlet.mvc.SimpleFormController;
  2. public class EditPersonController extends SimpleFormController {
  3. }

It does nothing for the moment, except allowing the test to compile.

To test this newly created controller, we need a HttpServletRequest and a HttpServletResponse object. These objects will be passed to the controller’s handleRequest method. Our test is, of course, not using a servlet engine that is able to create these objects for us, so we have to mock them. Here comes the use of the Spring’s MockHttpServletRequest and MockHttpServletResponse classes. With these objects, we can easily simulate a HTTP request that will be forwarded to our controller. We can then verify if a “GET” HTTP call will make our controller send the person form :


  1. /**
  2. * Tests the creation of a new Person.
  3. **/
  4. @Test
  5. public void testCreate() {
  6. MockHttpServletRequest request = new MockHttpServletRequest();
  7. request.setMethod("GET");
  8. ModelAndView mv = controller.handleRequest(request, new MockHttpServletResponse());
  9. assertEquals(controller.getFormView(), mv.getViewName());
  10. }

The ModelAndView object is used to determine which view the controller chose to send to the user.

Instead of doing :

assertEquals(controller.getFormView(), mv.getViewName());

We could have done :

import static org.springframework.test.web.ModelAndViewAssert.*;

[...]


assertViewName(mv, controller.getFormView());

[...]


Now the user is provided a form with two input fields. One for the “firstname” and one for the “lastname”. He fills those fields and submit the form. The controller is then called with the “fistname” and “lastname” posted by the user. It must normally save the person and return the “successView” which we named “personSaved” (see the XML context defined previously). Let’s now add this behavior to our test :


  1. import static org.springframework.test.web.ModelAndViewAssert.*;
  2. ...
  3. /**
  4. * Tests the creation of a new Person.
  5. **/
  6. @Test
  7. public void testCreate() {
  8. MockHttpServletRequest request = new MockHttpServletRequest();
  9. request.setMethod("GET");
  10. ModelAndView mv = controller.handleRequest(request, new MockHttpServletResponse());
  11. assertEquals(controller.getFormView(), mv.getViewName());
  12. request = new MockHttpServletRequest();
  13. request.setMethod("POST");
  14. request.setParameter("firstName", "Richard");
  15. request.setParameter("lastname", "Barabé");
  16. mv = controller.handleRequest(request, new MockHttpServletResponse());
  17. assertViewName(mv, controller.getSuccessView());
  18. }

So far we’ve tested that while creating a new Person, the user first asks the Person form (with an HTTP GET call), then submits that form (with an HTTP POST call that details person’s information) and is redirected to a success page when finished. We can say we tested the navigation part of the “create new Person” use case.


But, did the controller really saved the Person ? In other words : Did the controller called the PersonService’s save(Person p) method ? To test this, I will use EasyMock to mock a PersonService, tell EasyMock I want this PersonService’s save(Person p) method to be called once with the correct person, and then I will pass that PersonService mock to the controller. Once done, my test will know if the controller really called the PersonService adequately. Here is the code of the test :


  1. import static org.easymock.EasyMock.*;
  2. ...
  3. /**
  4. * Tests the creation of a new Person.
  5. **/
  6. @Test
  7. public void testCreate() {
  8. MockHttpServletRequest request = new MockHttpServletRequest();
  9. request.setMethod("GET");
  10. ModelAndView mv = controller.handleRequest(request, new MockHttpServletResponse());
  11. assertEquals("personForm", mv.getViewName());
  12. request = new MockHttpServletRequest();
  13. request.setMethod("POST");
  14. request.setParameter("firstName", "Richard");
  15. request.setParameter("lastname", "Barabé");
  16. // Create the service's imitation
  17. PersonService serviceMock = createMock(PersonService.class);
  18. controller.setPersonService(serviceMock);
  19. // The save method should be called with "Richard Barabé"
  20. serviceMock.save(new Person("Richard", "Barabé"));
  21. // The save method should be called only once
  22. expectLastCall().once();
  23. // Finished telling easymock how my service should be used.
  24. replay(serviceMock);
  25. mv = controller.handleRequest(request, new MockHttpServletResponse());
  26. assertViewName(mv, "personSaved");
  27. // Verify that the service have been used as we expect
  28. // (method save called once with "Richard Barabé")
  29. verify(serviceMock);
  30. }

For this to compile, I need to add a PersonService field and its getter/setter in the controller :


  1. import org.springframework.web.servlet.mvc.SimpleFormController;
  2. import myProject.PersonService;
  3. public class EditPersonController extends SimpleFormController {
  4. private PersonService service;
  5. public void setPersonService(PersonService service) {
  6. this.service = service
  7. }
  8. public PersonService getPersonService() {
  9. return this.service;
  10. }
  11. }

Now the test asserts the service has been called correctly. As we run it, we can see it fails with the following message :


java.lang.AssertionError:
Expectation failure on verify:
save(myProject.Person@1f2cea2): expected: 1, actual: 0
at org.easymock.internal.MocksControl.verify(MocksControl.java:82)
at org.easymock.EasyMock.verify(EasyMock.java:1410)
...

This just means our controller didn’t call the service’s save method as expected. Let’s make our controller do it’s job by adding the expected call :


  1. import org.springframework.web.servlet.mvc.SimpleFormController;
  2. import myProject.PersonService;
  3. public class EditPersonController extends SimpleFormController {
  4. private PersonService service;
  5. protected doSubmitAction(Object o) {
  6. this.service.save((Person) o)
  7. }
  8. public void setPersonService(PersonService service) {
  9. this.service = service
  10. }
  11. public PersonService getPersonService() {
  12. return this.service;
  13. }
  14. }

Running the test now should succeed. But, unfortunately, the bar is red again. For time consideration, I’ll leave aside the investigation and go right to the solution : we did not override the equals and hashcode methods of the Person class. Our controller that received the form submission did create a new Person, setting its first and last name. It then passed this new object to the doFormSubmitAction(Object) that called our mock passing the new person. But we told EasyMock we expected our service to be called with another Person object. Default implementation of the equals method in object makes the following statement false :

(new Person(”Richard”,”Barabé”)).equals(new Person(”Richard”,”Barabé”))

So let’s implement those hashCode and equals methods (I use Eclipse to generate this “boiler plate” code) :


  1. public class Person {
  2. private Long id;
  3. private String firstName;
  4. private String lastName;
  5. public Person(String firstName, String lastName) {
  6. this.firstName = firstName;
  7. this.lastName = lastName;
  8. }
  9. public Long getId() {
  10. return id;
  11. }
  12. private void setId(Long id) {
  13. this.id = id;
  14. }
  15. public String getFirstName() {
  16. return firstName;
  17. }
  18. public void setFirstName(String firstName) {
  19. this.firstName = firstName;
  20. }
  21. public String getLastName() {
  22. return lastName;
  23. }
  24. public void setLastName(String lastName) {
  25. this.lastName = lastName;
  26. }
  27. @Override
  28. public int hashCode() {
  29. final int prime = 31;
  30. int result = 1;
  31. result = prime * result
  32. + ((firstName == null) ? 0 : firstName.hashCode());
  33. result = prime * result
  34. + ((lastName == null) ? 0 : lastName.hashCode());
  35. return result;
  36. }
  37. @Override
  38. public boolean equals(Object obj) {
  39. if (this == obj)
  40. return true;
  41. if (obj == null)
  42. return false;
  43. if (getClass() != obj.getClass())
  44. return false;
  45. final Person other = (Person) obj;
  46. if (firstName == null) {
  47. if (other.firstName != null)
  48. return false;
  49. } else if (!firstName.equals(other.firstName))
  50. return false;
  51. if (lastName == null) {
  52. if (other.lastName != null)
  53. return false;
  54. } else if (!lastName.equals(other.lastName))
  55. return false;
  56. return true;
  57. }
  58. }

Now the code behaves correctly when we have two persons with the same fistName and lastName. And that green bar is back again.


There we are, we have successfully developped and tested our controller. This article is to be continued, and next time we’ll go over the Validator and View implementation.

No comments:

Post a Comment