Mock Test example of Springmvc Controller layer.

Source: Internet
Author: User
Tags object object response code

Spring Version:4.1.6.release

Junit version:2.4.5

Package Com.shiji.soc.es.controller;import static Org.junit.assert.*;import java.io.UnsupportedEncodingException; Import Java.util.arrays;import java.util.hashset;import Java.util.iterator;import Java.util.list;import Java.util.map;import Org.junit.before;import Org.junit.test;import Org.junit.runner.runwith;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.http.mediatype;import Org.springframework.mock.web.mockhttpservletresponse;import Org.springframework.test.context.contextconfiguration;import Org.springframework.test.context.junit4.springjunit4classrunner;import Org.springframework.test.web.servlet.mockmvc;import Org.springframework.test.web.servlet.mvcresult;import Org.springframework.test.web.servlet.resultactions;import Org.springframework.test.web.servlet.request.mockmvcrequestbuilders;import Org.springframework.test.web.servlet.setup.mockmvcbuilders;import Org.springframework.web.context.webapplicationcontext;import Com.fasterxml.jackson.Core. Jsonprocessingexception;import Com.fasterxml.jackson.databind.objectmapper;import Com.shiji.soc.es.dao.SocDao; Import Com.shiji.soc.es.dto.socfield;import Com.shiji.soc.es.dto.socrequest;import Com.shiji.soc.es.enums.fieldtype;import Com.shiji.soc.es.service.SocService; @SuppressWarnings ("Rawtypes") @ Contextconfiguration ({"Classpath:spring/soc-applicationcontext.xml", "Classpath:spring/soc-springmvc.xml"}) @ Runwith (springjunit4classrunner.class) public class Soccontrollertest {private static Objectmapper MAPPER = new OBJECTM    Apper ();    @Autowired Socdao Socdao;    @Autowired Socservice Socservice;    @Autowired Soccontroller Soccontroller;    protected MOCKMVC Mockmvc;    @Before public void Setup () {Mockmvc = Mockmvcbuilders.standalonesetup (Soccontroller). build ();        } @Test public void Testpostmethod () throws Exception {String Queryjson = This.getqueryjson ();                       Mvcresult Andreturn = Mockmvc. Perform (// mockmvcrequestbuilders//. Post ("/query")//. ContentType (Med Iatype.application_json)//. Content (Queryjson)//. Accept (Med        Iatype.application_json))//execute the request. Andreturn ();        Mockhttpservletresponse response = Andreturn.getresponse (); Response.getcontentasstring ();        Is the JSON string returned by the server controller. Response.getstatus ();        HTTP response code 200.  Response.getcookies ();    Server returned by cookie[] This.piringandassert (response); } @Test public void Testgetmethod () throws Exception {System.out.println ("Socdao is null?" + (Socdao = = Nu        ll));        System.out.println ("Socservice is null?" + (Socservice = = null));        System.out.println ("Soccontroller is null?" + (Soccontroller = = null));        System.out.println ("Mockmvc is null?" + (MOCKMVC = = null));            Mvcresult Mvcresult = this.mockMvc.perform (//    Mockmvcrequestbuilders.get ("/query")//). Andreturn ();        Mockhttpservletresponse response = Mvcresult.getresponse ();        String result = Response.getcontentasstring ();        System.out.println ("=====resp: \ n" + result);        System.out.println (Mvcresult.getresponse (). GetStatus ());        System.out.println ("Status:" + Response.getstatus ());        System.out.println ("Cookies:" + arrays.aslist (Response.getcookies ()));    SYSTEM.OUT.PRINTLN (response); } private void Piringandassert (Mockhttpservletresponse response) {try {System.out.println ("# # #statu            S: "+ response.getstatus ());            String Contentasstrin = null;            Contentasstrin = Response.getcontentasstring ();            System.out.println (Contentasstrin);            Map readvalue = Mapper.readvalue (Contentasstrin, Map.class);            List List = (list) readvalue.get ("results"); if (list = = null) {System.out.println ("# # #result is nulL!!            ");                } else {for (object object:list) {System.out.println (object);            }} System.out.println ("# # #page =" + readvalue.get ("page"));            System.out.println ("# # #size =" + readvalue.get ("size"));            System.out.println ("# # #count =" + Readvalue.get ("Count"));            System.out.println ("# # #respCode =" + Readvalue.get ("Respcode"));            System.out.println ("# # #respText =" + Readvalue.get ("Resptext"));        System.out.println ("# # #errorCode =" + Readvalue.get ("ErrorCode"));        } catch (Exception e) {e.printstacktrace ();        }} private String Getqueryjson () {hashset<string> set = new hashset<string> ();        Set.add ("apiPassword10030");        Set.add ("apiPassword10064");        Set.add ("apiPassword10142");        Set.add ("apiPassword10129");        Socrequest bean = new Socrequest (); list<socfield> query = arrays.aslist (//New Socfield ("GroupId", FieldType.MATCH.getType (), 0),//New Socfield ("Apipassword", Fiel DType.SET.getType (), SET),//New Socfield ("Txndatetime", FieldType.RANGE.getType (), 1496817450449L, 149681        7455610L)//);        Bean.setquery (query);        list<string> column = Arrays.aslist ("Txnno", "Txndatetime", "Terid", "Apiuser");        Bean.setcolumns (column);        Bean.setpage (1);        Bean.setsize (20);        String writevalueasstring = null;        try {writevalueasstring = mapper.writevalueasstring (bean);        } catch (Jsonprocessingexception e) {e.printstacktrace ();    } return writevalueasstring; }}

  

Mock Test example of Springmvc Controller layer.

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.