Spring MVC Controller Unit Test

Source: Internet
Author: User
Tags file handling

Introduction

Unit Testing 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 simpler and more efficient as the functionality improves.

Here is an example of version 4.1 documenting the unit test flow for a controller. 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

Use MAVEN to build your project with the following structure:

Testing at the controller layer does not require a separate spring config, you can directly use the. xml

in Src/main/java Here's a note of the Spring MVC context Configuration policy:

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

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

      • root-context.xml (file, place can be servle Resources used by the T and filter shares)
      • appservlet (directory)
        • controllers.xml (file, controller-related configuration)
        • servlet-context.xml (file, place a resource with servlet)

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

1 <Web-appxmlns= "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 -Ten  One <Context-param> A  - <Param-name>Contextconfiglocation</Param-name> -  the <Param-value>/web-inf/spring/root-context.xml</Param-value> -  - </Context-param> -  + <!--creates the Spring Container shared by all servlets and Filters - -  + <Listener> A  at <Listener-class>Org.springframework.web.context.ContextLoaderListener</Listener-class> -  - </Listener> -  - <Filter> -  in <Filter-name>Csrffilter</Filter-name> -  to <Filter-class>Org.springframework.web.filter.DelegatingFilterProxy</Filter-class> +  - <async-supported>True</async-supported> the  * </Filter> $ Panax Notoginseng <filter-mapping> -  the <Filter-name>Csrffilter</Filter-name> +  A <Url-pattern>/*</Url-pattern> the  + </filter-mapping> -  $ <!--Processes Application Requests - $  - <servlet> -  the <Servlet-name>Appservlet</Servlet-name> - Wuyi <Servlet-class>Org.springframework.web.servlet.DispatcherServlet</Servlet-class> the  - <Init-param> Wu  - <Param-name>Contextconfiglocation</Param-name> About  $ <Param-value>/web-inf/spring/appservlet/servlet-context.xml</Param-value> -  - </Init-param> -  A <Load-on-startup>1</Load-on-startup> +  the <async-supported>True</async-supported> -  $ </servlet> the  the <servlet-mapping> the  the <Servlet-name>Appservlet</Servlet-name> -  in <Url-pattern>/</Url-pattern> the  the </servlet-mapping> About  the <!--disables Servlet Container welcome file handling. Needed for compatibility with Servlet 3.0 and Tomcat 7.0 - the  the <welcome-file-list> +  - <Welcome-file></Welcome-file> the Bayi </welcome-file-list> the  the </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.

 Packagepairwinter.spring.mvc.controller.test;Import StaticOrg.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;Import Staticorg.springframework.test.web.servlet.result.MockMvcResultMatchers.content;Import StaticOrg.springframework.test.web.servlet.result.MockMvcResultMatchers.status;Import StaticOrg.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;ImportOrg.junit.Before;Importorg.junit.Test;ImportOrg.junit.runner.RunWith;Importorg.springframework.samples.mvc.AbstractContextControllerTests;ImportOrg.springframework.test.context.junit4.SpringJUnit4ClassRunner;ImportORG.SPRINGFRAMEWORK.TEST.WEB.SERVLET.MOCKMVC; the @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.