Testing the controller layer in SPRING-MVC is generally cumbersome because there is no such context in the Web container, and it is not elegant to start the container test.
Maven dependency, which needs to be noted is the use of Spring-test-mvc, such a framework.
<dependency> <groupId>org.springframework</groupId> <artifactid>spring-core</artifactid> <version>3.2.13.release </version></dependency><dependency> <groupId> Org.springframework</groupid> <artifactid>spring-webmvc</artifactid> <version>3.2.13.RELEASE</version></dependency><dependency> <groupId>org.springframework</groupId> < Artifactid>spring-test</artifactid> <version>3.2.13.release</version > <scope>test</scope></dependency><dependency> <groupId>org.springframework</groupId> <artifactId> spring-test-mvc</artifactid> <version>1.0.0.m1</version> <scope>test</scope></ Dependency>
Slightly different from the normal spring test is an annotated @WebAppConfiguration, which uses the mock object Mockmvc, which is Spring-test-mvc Something in the framework, the Java code is as follows:
Package com.spring.demo.web.controller;import static org.junit.assert.assertnotnull;import static org.springframework.test.web.server.request.mockmvcrequestbuilders.get;import static org.springframework.test.web.server.result.MockMvcResultMatchers.forwardedUrl;import static Org.springframework.test.web.server.result.mockmvcresultmatchers.status;import org.junit.before;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.autowired;import org.springframework.test.context.contextconfiguration;import org.springframework.test.context.junit4.springjunit4classrunner;import org.springframework.test.context.web.webappconfiguration;import org.springframework.test.web.server.mockmvc;import org.springframework.test.web.server.setup.mockmvcbuilders;import Org.springframework.web.context.webapplicationcontext;import com.spring.demo.init.appconfig;import com.spring.demo.init.web.mvcconfig;/** * using mock objects to test controller * * @ author sean * */@WebAppConfiguration @runwith (springjunit4classrunner.class) @ Contextconfiguration (CLASSES&NBSP;=&NBSP;{&NBSP;APPCONFIG.CLASS,&NBSP;MVCCONFIG.CLASS&NBSP;}) Public class PingControllerTest { @Autowired private webapplicationcontext applicationcontext; private mockmvc mockmvc; @Before public void setup () { mockMvc = MockMvcBuilders .webapplicationcontextsetup (ApplicationContext). Build (); } @Test public void test () Throws exception { &nbSp; assertnotnull (MOCKMVC); Mockmvc.perform (Get ("/ping/show")). Andexpect (Status (). IsOk ()) .andexpect (Forwardedurl ("/web-inf/pages/ping/show.jsp")); }}
For specific items, please refer to Springdemo
SPRING-MVC JUnit Test