Spring MVC Controller unit test, springmvc

Source: Internet
Author: User
Tags file handling

Spring MVC Controller unit test, springmvc

Introduction

The unit test on the Controller layer can improve the reliability of applications. Although this increases the development time, it is necessary to lose. Here I think it is much more than lost.

The Unit Testing Method After Sping MVC3.2 has changed. With the improvement of functions, unit testing is simpler and more efficient.

Take version 4.1 as an example to record the unit test process of Controller. Spring MVC Showcase (https://github.com/spring-projects/spring-mvc-showcase), which is used in the current version 4.1.0, will be changed in the future, in order to make the project run, refer to its updated configuration.

The ide I use is IntelliJ IDEA13. I personally think it is much easier to use than Eclipse. It is paid and expensive!

Project Structure

Build a project using maven. The project structure is as follows:

In the Controller layer test, you do not need to write a separate Spring config. You can directly use. xml in src/main/java.

Here we record the Configuration Policy of Spring Mvc context:

A lot of friends will configure a lot of things in a file (e. g spring-mvc.xml) to see the web configuration structure in showcase

  • WEB-INF
    • Web. xml (file)
    • Spring (folder)

      • Root-context.xml (file, placing resources that can be shared by servlet and filter)
      • AppServlet (directory)
        • Controllers. xml (file, Controller-related configuration)
        • Servlet-context.xml (file, with resources used by servlet)

Spring mvc is the packaging of Servlet, so that it can be structured and streamlined.

 1 <web-app xmlns="http://java.sun.com/xml/ns/javaee" 2  3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4  5 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 6  7 version="3.0"> 8  9 <!-- The definition of the Root Spring Container shared by all Servlets and Filters -->10 11 <context-param>12 13 <param-name>contextConfigLocation</param-name>14 15 <param-value>/WEB-INF/spring/root-context.xml</param-value>16 17 </context-param>18 19 <!-- Creates the Spring Container shared by all Servlets and Filters -->20 21 <listener>22 23 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>24 25 </listener>26 27 <filter>28 29 <filter-name>csrfFilter</filter-name>30 31 <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>32 33 <async-supported>true</async-supported>34 35 </filter>36 37 <filter-mapping>38 39 <filter-name>csrfFilter</filter-name>40 41 <url-pattern>/*</url-pattern>42 43 </filter-mapping>44 45 <!-- Processes application requests -->46 47 <servlet>48 49 <servlet-name>appServlet</servlet-name>50 51 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>52 53 <init-param>54 55 <param-name>contextConfigLocation</param-name>56 57 <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>58 59 </init-param>60 61 <load-on-startup>1</load-on-startup>62 63 <async-supported>true</async-supported>64 65 </servlet>66 67 <servlet-mapping>68 69 <servlet-name>appServlet</servlet-name>70 71 <url-pattern>/</url-pattern>72 73 </servlet-mapping>74 75 <!-- Disables Servlet Container welcome file handling. Needed for compatibility with Servlet 3.0 and Tomcat 7.0 -->76 77 <welcome-file-list>78 79 <welcome-file></welcome-file>80 81 </welcome-file-list>82 83 </web-app>

 

We can see that the separate configuration makes the file more effective.

This part of the configuration file is used to configure the web context. There are other modules in the project, such as DAO and Service. Their corresponding applicationContext files will be placed in the src/main/resource Directory.

A complete unit test includes a unit test of service. We won't talk about it here, but the unit test of Controller still needs to call service and DAO. Pay attention to the introduction of applicationContext of Service and DAO.

Controller Unit Test

The test class contains these three comments. It is not difficult to understand the meaning of the comments, but mainly understand the use of ContextConfiguration.

@ RunWith (SpringJUnit4ClassRunner. class)

@ WebAppConfiguration // The default value is src/main/webapp.

@ ContextConfiguration ("file: src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml ")

Note: Here @ ContextConfiguration only parses the servlet-context.xml, if there are other modules in the project applicationContext, you also need to introduce them in otherwise the Service is null.

For example

@ ContextConfiguration ({

"File: src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml ",

"Classpath *: springxml/**. xml"

})

You can complete a Controller unit test by adding other code. The following is an example. For more examples, see the content in showcase.

package pairwinter.spring.mvc.controller.test;import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;import org.junit.Before;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.samples.mvc.AbstractContextControllerTests;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import org.springframework.test.web.servlet.MockMvc;@RunWith(SpringJUnit4ClassRunner.class)@WebAppConfiguration@ContextConfiguration({"file:src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml",“classpath*: springxml/**.xml”})public class ControllerTests{@Autowiredprivate WebApplicationContext wac;private MockMvc mockMvc;@Beforepublic void setup() throws Exception {this.mockMvc = webAppContextSetup(this.wac).build();}@Testpublic void controllerExceptionHandler() throws Exception {this.mockMvc.perform(get("/test")).andExpect(status().isOk());}}

 


How does Spring work in mvc?

Spring MVC is a follow-up product of SpringFrameWork and has been integrated into Spring Web Flow.
Edit the Spring MVC Framework
The Spring framework provides a full-featured MVC module for Building Web applications. Using Spring-pluggable MVC Architecture, you can choose whether to use a built-in Spring Web framework or a Web framework such as Struts. Through the policy interface, the Spring framework is highly configurable and contains multiple view technologies, such as assumerver Pages (JSP), Velocity, Tiles, iText, and POI. The Spring MVC Framework does not know the view used, so it does not force you to only use JSP technology. Spring MVC separates the roles of controllers, model objects, schedulers, and processing program objects, making them easier to customize.
Edit Spring MVC in this section. Advantages:
Lifecycle for overriding binding, validation, etc.; it is easy to seamlessly integrate with other View frameworks (such as Titles) and easy to test using IOC. It is a typical textbook-style mvc Architecture, unlike struts, which is a variant or a framework not completely based on the mvc system, for beginners or those who want to know mvc, I think spring is the best. Its implementation is a textbook! Second, it is a pure servlet system like tapestry, which is also its advantage over struts. The framework itself has code, and it does not seem easy to understand.
Edit this section about Spring MVC Controller layer Unit Testing
Test preparation: 1. Build a test Web environment @ RunWith (UnitilsJUnit4TestClassRunner. class) @ SpringApplicationContext ({"classpath :*. xml "," file: src/main/webapp/WEB-INF/spring-configuration /*. xml "," file: src/main/webapp/WEB-INF /*. xml "}) 2. Inject the Controller class @ SpringBeanByType BeanController; 3. Write test data. The file name must be the same as that of the test class, for example, BeanControllerTest. xml, test class BeanControllerTest. 4. Inject Test data @ Test @ DataSet public void testBean (){}

How do I write a unit test for a web project with a spring mvc structure to test the structure output by the dao layer (the layers have dependencies )?

The test team of the web project will test the correctness of the business section, initialize Spring in junit, obtain the dao class, and call the dao class method for testing.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.