Using JUnit to test the SPRINGMVC controller

Source: Internet
Author: User

This article turns from Http://www.tuicool.com/articles/7rMziy

Usually to JUnit test Service/dao layer is already very familiar with, if not understand, can poke here, but we want to test controller layer, not always restart the server bar, (restart Tomcat good slow drift over, don't ...) Don't go), then we'll test the controller layer using the JUNIT4 simulation request.

Code Listing 1: Direct Controller invocation method

ImportStatic org.junit.assert.*;Import java.sql.SQLException;Import Org.junit.Before;Import Org.junit.Test;Import Org.junit.runner.RunWith;Import org.springframework.beans.factory.annotation.Autowired;Import Org.springframework.mock.web.MockHttpServletRequest;Import Org.springframework.mock.web.MockHttpServletResponse;Import org.springframework.test.context.ContextConfiguration;Import Org.springframework.test.context.junit4.SpringJUnit4ClassRunner;Import Com.zz.login.web.LoginController;/** *@author Zhzh * 2015-4-7 * *@RunWith (Springjunit4classrunner.class)@ContextConfiguration ({"Classpath*:/beans.xml","Classpath*:/spring-mvc.xml"})PublicClassTestController {Analog Request,responseprivate Mockhttpservletrequest request;Private Mockhttpservletresponse response;Inject Logincontroller@AutowiredPrivate Logincontroller Logincontroller;Initialize the simulation request,response before executing the test method@BeforePublicvoidSetUp() {request =New Mockhttpservletrequest (); Request.setcharacterencoding ("UTF-8"); Response = new Mockhttpservletresponse ();} /** * * @Title: Testlogin * @Description: Test User Login * /@Test public  void testlogin() { T ry {request.setparameter ("UserName", "admin") request.setparameter ("password", "2"); Assertequals ("Login", Logincontroller.loginin (Request,response));} catch (Exception e) {e.printstacktrace ();}} }

Code Listing 2: Calling the request path

ImportStatic org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;ImportStatic org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;ImportStatic org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;ImportStatic Org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;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.transaction.TransactionConfiguration;Import org.springframework.test.context.web.WebAppConfiguration;Import ORG.SPRINGFRAMEWORK.TEST.WEB.SERVLET.MOCKMVC;Import org.springframework.transaction.annotation.Transactional;Import Org.springframework.web.context.WebApplicationContext;/** *@author Zhzh * 2015-4-7 * *@RunWith (Springjunit4classrunner.class)@WebAppConfiguration@ContextConfiguration ({"Classpath*:/beans.xml","Classpath*:/spring-mvc.xml"})Of course, you can declare that a transaction manages each unit test to perform a transaction rollback, whether successful or not@TransactionConfiguration (Defaultrollback =True@TransactionalPublicClassTestController2 {@AutowiredPrivate Webapplicationcontext WAC;Private MOCKMVC Mockmvc;@BeforePublicvoidsetup () {THIS.MOCKMVC = Webappcontextsetup (THIS.WAC). Build ();}  @Test public void testlogin () throws Exception {mockmvc.perform (post (" UserName ", " admin "). Param (" password ", /* @Test//Some unit tests you do not want to roll back @Rollback (false) public void Testinsert () throws Exception {Mockmvc . Perform ((Post ("/inserttest")). Andexpect (Status (). IsOk ()). Anddo (print ()); } */} 
Note: Import static Spring Class Code 3:

Logincontroller Code Snippets

/** * Login Portal * @paramRequest * @paramresponse * @return */@RequestMapping (value =  "/logintest", method = Requestmethod.post) public string loginTest ( HttpServletRequest request,httpservletresponse response) {string account = request.getparameter (  "UserName"); string password = request.getparameter (  "password"); if (account.equals ( "admin") &&password.equals (else{return  "login";}}       

Reference: http://blog.csdn.net/a95473004/article/details/8926929

http://ysj5125094.iteye.com/blog/2082110

Using JUnit to test the SPRINGMVC controller

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.