Utilize Spring mock objects and Spring's extensions to the JUnit framework to simplify unit testing for Spring Web components.
December 01, 2005
URL:http://www.drdobbs.com/simplify-unit-testing-for-spring-web-com/212903199
Testability is one of the key principles behind the Spring framework (i.e., the ability to test each component in the framework regardless of its nature). In this sense, Spring was a major improvement over the core J2EE model, in which the components were hard to test outside of the container. Even in-container testing required significant and often complicated setup. (See Sidebar: Why Testability Is Important.)
This article describes Spring's testability features, specifically the practical features that make unit testing Web components as easy as testing plain old Java objects (POJOs).
Spring provides a mock implementation for each key interface from the Web side of the J2EE spec:
As already stated, you most likely will find the most use for mock HttpServletRequest, HttpServletResponse, and HttpSession while testing your controllers. However, Spring also provides the following mock implementations to other less frequently used components that you may find useful on their own, especially if you are an API developer:
So, what does it take to use these mock objects? As you know, HttpServletRequest is a component that holds immutable values that represent HTTP parameters. These parameters are what drive the functionality of the Web components. MockHttpServletRequest, which is an implementation of the HttpServletRequest interface, allows you to set these otherwise immutable parameters. In a typical Web component-testing scenario, you can instantiate this object and set any of the parameters as follows:
//specify the form method and the form action MockHttpServletRequest request = new MockHttpServletRequest("GET", ""); request.addParameter("choice", expanded); request.addParameter("contextMenu", "left");
Similarly, you can instantiate, fully manipulate, and examine the HttpResponse and HttpSession objects.
Now let's see how you can make JUnit tests Spring-aware.
Terms of Service | Privacy Statement | Copyright © 2024 UBM Tech, All rights reserved.