Before we tested the controller just as a pojo for a simple test, after spring3.2 we can follow the controller's way to test the Spring MVC controller, so when the test controller, There is no need to start the Web server and Web browser again, the following is the test code:
ImportCom.darling.controller.TestController;Importorg.junit.Test;ImportORG.SPRINGFRAMEWORK.TEST.WEB.SERVLET.MOCKMVC;Importorg.springframework.test.web.servlet.ResultActions;ImportOrg.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;Importorg.springframework.test.web.servlet.request.MockMvcRequestBuilders;Importorg.springframework.test.web.servlet.result.MockMvcResultMatchers;Importorg.springframework.test.web.servlet.setup.MockMvcBuilders;/** * @author* @date 2018/9/5 11:17 * @description Test Spring 3.2 New test feature added*/ Public classTestdemo {@Test Public voidTesttestcontroller ()throwsexception{TestController Controller=NewTestController (); MOCKMVC Mockmvc=Mockmvcbuilders.standalonesetup (Controller). build (); Mockhttpservletrequestbuilder Builder= Mockmvcrequestbuilders.get ("/test/testjsp"); Resultactions Actions=Mockmvc.perform (builder); Actions. Andexpect (Mockmvcresultmatchers.view (). Name ("Index")); }}
It can be seen from the code that we sent a/testjsp request to TestController and asserted that the name of the result view is index It first passes a TestController instance to Mockmvcbuilders.standalonesetup () and calls build () to build the MOCKMVC instance. It then uses the MOCKMVC instance to perform a GET request for "/" and sets the desired view name. Throws an exception if the asserted view name is inconsistent with the controller return
This test spring3.2 introduced new features, recorded only as a memo, the personal feel that the conditions allow the case is more willing to use the browser to test;
Test controller with MOCKMVC