Expert Spring MVC and Web Flow

(Dana P.) #1
We are using an org.springframework.mock.web.MockHttpServletRequestto simulate an
HttpServletRequestobject. Spring provides a complete set of mock objects for the servlet
environment, making it easy to write tests for your Spring MVC components that will run out-
side of a container. We will cover testing of Spring MVC applications in a future chapter, but
for now it’s sufficient to know that these mock classes allow us to control and simulate the
external elements of a web request, such as an HttpServletRequestor HttpServletResponse.

Listing 6-7.Simple DataBinder TestCase

public class CommandBeanBindingTest extends TestCase {

private Name name;
private ServletRequestDataBinder binder;
private MockHttpServletRequest request;

public void setUp() throws Exception {
name = new Name();
binder = new ServletRequestDataBinder(name, "nameBean");
request = new MockHttpServletRequest();
}

public void testSimpleBind() {
// just like /servlet?firstName=Anya&lastName=Lala
request.addParameter("firstName", "Anya");
request.addParameter("lastName", "Lala");

binder.bind(request); // performed by BaseCommandController
// on submit so you don’t have to

assertEquals("Anya", name.getFirstName()); // true!
assertEquals("Lala", name.getLastName()); // true!
}
}

Note that when using the BaseCommandControlleror its subclasses, the actual bind()call
is performed automatically. By the time your code obtains the command bean, it will be cre-
ated and populated by request parameter values. We explicitly show it here so that you may
understand what is going on under the hood.
The ServletRequestDataBinderis initialized with the bean to be populated and the name
nameBean. This name is used when generating an Errors instance and error messages, in the case
of errors during binding. The name can be any String, though it is best to use names that are
easily compatible with properties files (which is where you typically define error messages). If
not provided the name will default to target. However, when this DataBinderis used in the MVC
framework, the default name of the JavaBean is command.
The unit test in Listing 6-7 creates a MockHttpServletRequestso we can illustrate how the
request is actually bound to the bean. We simulate a request submission by adding parame-
ters, being careful to match the parameter name to the name of the property on the bean. The
bind()method then delegates to a BeanWrapperImplclass to translate the string expressions,

126 CHAPTER 6 ■THE CONTROLLER MENAGERIE

Free download pdf