Spring MVC Controller Unit Test

Source: Internet
Author: User
Tags file handling

Brief introduction

The unit test of the controller layer can improve the reliability of the application, although this makes the development of the time has increased, there will be lost, here I think to get more than lost.

The unit test method after the Sping MVC3.2 version has changed, and unit testing is much simpler and more efficient as the functionality improves.

The unit test process for the controller is documented here in version 4.1. It is well worth referring to spring MVC Showcase (https://github.com/spring-projects/spring-mvc-showcase), Its current version is using 4.1.0 and will be changed later, in order for the project to run, please refer to its updated configuration.

I use the IDE is IntelliJ IDEA13, I personally think it is more useful than eclipse, is paid, very expensive!

Project structure

Using MAVEN to build your project, the project structure is as follows:

The controller layer test does not need to write a separate spring config, you can directly use the. XML in the Src/main/java

Here is a note of the Spring MVC context configuration strategy:

A lot of small partners will be in a file (e.g Spring-mvc.xml) configuration of many things, to see the configuration structure of the Web in showcase

    • Web-inf
      • Web. XML (file)
      • Spring (folder)

        • Root-context.xml (files, placing resources that can be used by Servlets and filter shares)
        • Appservlet (catalogue)
          • Controllers.xml (file, controller-related configuration)
          • Servlet-context.xml (file, place the resource used by the servlet)

Spring MVC is a wrapper over the servlet, enabling it to be structured and process-enabled.


<web-app xmlns= "Http://java.sun.com/xml/ns/javaee" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi: schemalocation= "Http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version= " 3.0 "><!--the definition of the Root Spring Container shared by all servlets and Filters--><context-param> <param-name>contextconfiglocation</param-name><param-value>/web-inf/spring/root-context.xml </param-value></context-param><!--creates the Spring Container shared by all servlets and Filters-->& Lt;listener><listener-class>org.springframework.web.context.contextloaderlistener</listener-class ></listener><filter><filter-name>csrfFilter</filter-name><filter-class> org.springframework.web.filter.delegatingfilterproxy</filter-class><async-supported>true</ async-supported></filter><filter-mapping><filter-name>csrffilter</filter-name>< url-pattern>/*</url-pattern></filter-mapping><!--Processes Application Requests--><servlet ><servlet-name>appServlet</servlet-name><servlet-class> Org.springframework.web.servlet.dispatcherservlet</servlet-class><init-param><param-name> contextconfiglocation</param-name><param-value>/web-inf/spring/appservlet/servlet-context.xml</ Param-value></init-param><load-on-startup>1</load-on-startup><async-supported>true </async-supported></servlet><servlet-mapping><servlet-name>appservlet</servlet-name ><url-pattern>/</url-pattern></servlet-mapping><!--disables servlet Container welcome file Handling. Needed for compatibility with Servlet 3.0 and Tomcat 7.0--><welcome-file-list><welcome-file></ Welcome-file></welcome-file-list></web-app>




Can see separate configuration, so that the role of the file is more clear.

This section of the configuration file is to configure the Web context, the project also has other module, such as Dao,service, their corresponding applicationcontext file will be placed in the Src/main/resource directory.

The complete unit test, of course, has a unit test of the service, which is not said, but the controller's unit tests also need to invoke service and DAO, pay attention to the introduction of service and DAO ApplicationContext.

Controller Unit Test

Including these three comments in the test class, it is not difficult to understand their role in terms of surface meaning, the main understanding of the use of contextconfiguration.

@RunWith (Springjunit4classrunner.class)

@WebAppConfiguration//default is Src/main/webapp

@ContextConfiguration ("File:src/main/webapp/web-inf/spring/appservlet/servlet-context.xml")

Note: The @contextconfiguration here only resolves the servlet-context.xml, if there are other modules in the project ApplicationContext, also need to introduce them to the otherwise received service is null.

For example

@ContextConfiguration ({

"File:src/main/webapp/web-inf/spring/appservlet/servlet-context.xml",

"Classpath*: Springxml/**.xml"

})

Add a little bit of code to complete a controller unit test, here is an example, more examples please refer to 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 ());}}



Spring MVC Controller Unit Test

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.