Test controller with MOCKMVC

Source: Internet
Author: User

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

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.