The interface test of Jetty simulation server as test pile is introduced in detail __jetty as Test pile interface test

Source: Internet
Author: User
Tags flush format message getmessage pack readfile response code soapui

Sometimes, when the interface is tested, often need to rely on external interface environment, but in the actual development, especially in the agile development model, many times depending on the external interface environment may be impassability or not completed, this time can not be carried out in a timely manner end-to-end testing, the need to test the pile is very important. in my previous article, I have introduced the use of Third-party tools soapui as a test pile for testing the interface test, see http://blog.csdn.net/russ44/article/details/52230355
However, since SOAPUI is typically deployed on a local Windows environment (the Linux environment has not been used, not recommended), and the test environment is typically deployed on a Linux server, there may be situations where the test environment is not able to tune in to the local environment. This is another way to deploy to the Linux server for interface testing, detailed as follows:
first, test pile project
Shaoxing
1. Jetty Introduction:

Jetty is an open source servlet container, it is a Java based web container, ease of use is the basic principle of Jetty design, details can be Baidu's

Required Jar Pack (Me):


2. Test Pile Purpose:

In the test, the tester especially in the interface testing, often need to use the test pile to test, usually, the corresponding developers will write the corresponding test pile, as a jar package as a service to the client to invoke (when the interface is not scheduled or delayed, Testers should lead the test pile to the developer's request, depending on the actual situation.

3. Test Pile principle

It is equivalent to start a jetty container, intercept the corresponding request, and return the corresponding message.

4. Test pile Use Process

1. Write a Java class with the main function (this main function launches a jetty container) under the server package, configure the port number, the request to intercept, and the corresponding servlet to process the request

<span style= "FONT-SIZE:18PX;"

>package Cn.migu.server;
Import Org.eclipse.jetty.server.Server;
Import Org.eclipse.jetty.servlet.ServletContextHandler;

Import Org.eclipse.jetty.servlet.ServletHolder;
Import Cn.migu.servlet.JsonResponseDemo;
Import Cn.migu.servlet.XmlResponseDemo;

Import Cn.migu.util.Log4jUtil;  /** * <Description> Service Portal Configuration * @author Yanlu * * */public class Httpserverdemo {//private static log4jutil log =
	
	New Log4jutil (HttpServerDemo.class.getName ()); /** * Main Method entry * * @param args/public static void main (string[] args) {try {server server = new Server
			(19993);
			Specifies the port number of the service Servletcontexthandler the context = new Servletcontexthandler (servletcontexthandler.sessions);
			A context is a web-application context.setcontextpath ("/test");
			Access to Project name (path) server.sethandler (context); The path of the servlet map, similar to the web.xml servlet url-pattern definition context.addservlet (new Servletholder (), New Xmlresponsedemo ()), "/
			Channelfaqsearch "); TwoThe parameters are the servlet that intercepts the request and the path that you want to intercept Context.addservlet (new Servletholder (New Jsonresponsedemo ()), "/executecampaign");
			Log.info ("server start.");

			SYSTEM.OUT.PRINTLN ("server start.");
			Start service Server.start ();
		Server.join ();
		catch (Exception e) {e.printstacktrace (); }} </span>

2. Process the request in the servlet and return the message (the main purpose of the test pile is to simulate the interface and return the message.) Request to deal with what's on the skim ~)

<1> processing XML format Response message, coding as follows:

<span style= "FONT-SIZE:18PX;"

>package Cn.migu.servlet;

Import java.io.IOException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;

Import Javax.servlet.http.HttpServletResponse;
Import Cn.migu.util.ConfigUtil;
Import cn.migu.util.GlobalSettings;
Import Cn.migu.util.Log4jUtil;
Import Cn.migu.util.OutPrinterUtil;
Import Cn.migu.util.XMLReaderHelper;

	/** * <Description> intercept execution activity request, return XML format message * @author Yanlu */public class Xmlresponsedemo extends HttpServlet {

	Private Log4jutil log = new Log4jutil (This.getclass (). GetName ()); @Override public void DoPost (HttpServletRequest request, httpservletresponse response) throws IOException {STRINGB
			
			Uilder Builder;
			String FilePath = "/apps/stub_test/responseprofile/channelfaqsearch.xml";
			String FilePath = Globalsettings.getproperty ("Channelfaqsearch");
			Reads an external XML file String FilePath = ConfigUtil.CONFIG.get ("Channelfaqsearch"); Converts an XML file to string string xmlstr = Xmlreaderhelper.xmlstrreader (FilePath); if (!) ( NULL = = Xmlstr) {System.out.println ("read XML succeeded.)
			    ");
			Builder = new StringBuilder (XMLSTR); else {System.out.println ("failed to read XML.")
			    ");
			    Builder = new StringBuilder (1024);
			Bindbuilder (builder);
    }//Response XML format string outprinterutil.outputxml (response, builder);
        @Override public void doget (HttpServletRequest request, httpservletresponse response) throws IOException {
    With DoPost method DoPost (request, response); } private void Bindbuilder (StringBuilder builder) {builder.append ("<?xml version=\" 1.0\ "encoding=\" utf-8\ "
        ?><notifyrsp> ");
        Builder.append ("<transId>" + "cs112233" + "</transId>");
        Builder.append ("<processTime>" + "230ms" + "</processTime>");
        Builder.append ("<cpId>710302</cpId>");
        Builder.append ("<bulletinType>1</bulletinType>"); Builder.append ("<bulletinid>1</bulletInid> ");
        Builder.append ("<bulletinID>1</bulletinID>");
        Builder.append ("<returnCode>0000</returnCode>");
        Builder.append ("<bulletinTitle> Blackout announcement </bulletinTitle>");
        Builder.append ("<bulletinCont> October 31 Blackout </bulletinCont>");
        Builder.append ("<publishTime>20151021101212</publishTime>");
        Builder.append ("<publishType>0</publishType>");
        Builder.append ("<bulletinLevel>0</bulletinLevel>");
        Builder.append ("<contactType>1</contactType>");
        Builder.append ("<needReply>1</needReply>");
        Builder.append ("<adminName> Administrator </adminname >");
        Builder.append ("<bulletinAttachs>");
        Builder.append ("<bulletinAttach>");
        Builder.append ("<attachName> Appendix 1 </attachname >");
        Builder.append ("<attachType> 1 </attachtype >"); Builder.append ("&LT;ATTACHURL&GT
        Ftp://192.168.1.1/test.doc</attachurl> ");
        Builder.append ("</bulletinAttach>");
        Builder.append ("<bulletinAttach>");
        Builder.append ("<attachName> Appendix 2 </attachname >");
        Builder.append ("<attachType> 2 </attachtype >");
        Builder.append ("<attachurl > ftp://192.168.1.1/test2.doc</attachurl>");
        Builder.append ("</bulletinattach >");
        Builder.append ("</bulletinattachs >");
        Builder.append ("<replys >");
        Builder.append ("<reply >");
        Builder.append ("<replytime > 20151011121212 </replytime >");
        Builder.append ("<replytype > 1 </replytype >");
        Builder.append ("<replycont > CP reply Test 1 </replycont >");
        Builder.append ("<replyattchs >");
        Builder.append ("<replyattch >");
        Builder.append ("<attachname > Annex 1 </attachname >"); Builder.append ("<attachurL > ftp://192.168.1.1/test.doc</attachurl> ");
        Builder.append ("</replyattch >");
        Builder.append ("</replyattchs >");
        Builder.append ("</reply >");
        Builder.append ("<reply >");
        Builder.append ("<replytime > 20151011121212 </replytime >");
        Builder.append ("<replytype > 2 </replytype >");
        Builder.append ("<replycont > Admin reply Test 1 </replycont >");
        Builder.append ("<replyattchs >");
        Builder.append ("<replyattch >");
        Builder.append ("<attachname > Annex 1 </attachname >");
        Builder.append ("<attachurl > ftp://192.168.1.1/test.doc</attachurl>");
        Builder.append ("</replyattch >");
        Builder.append ("</replyattchs >");
        Builder.append ("</reply >");
        Builder.append ("</replys >");
    Builder.append ("</notifyRsp>"); }} </span>

<2> processing JSON format Response message, coding as follows:
<span style= "FONT-SIZE:18PX;"

>package Cn.migu.servlet;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;

Import Javax.servlet.http.HttpServletResponse;
Import Cn.migu.util.ConfigUtil;
Import Cn.migu.util.FileUtil;
Import cn.migu.util.GlobalSettings;

Import Cn.migu.util.OutPrinterUtil;

Import java.io.IOException; 
    /** * <Description> intercept Execute activity request, return JSON format message * @author Yanlu * * */public class Jsonresponsedemo extends HttpServlet { @Override protected void DoPost (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, Ioexce
    	ption {//string FilePath = "/apps/stub_test/responseprofile/executecampaign.json";
        
        String FilePath = ConfigUtil.CONFIG.get ("Executecampaign");
        
        Converts the JSON file to string string resultjson= fileutil.readfile (FilePath);
    Responds to JSON format Strings Outprinterutil.outputjson (Resultjson, RESP); } @Override protected void doget (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException {
    DoPost (req, resp); }} </span>

Important NOTE:

<1> files are stored in the following locations:

<span style= "FONT-SIZE:18PX;" > #配置文件路径
#文件置于当前工程的profile目录下
#ChannelFaqSearch =./profile/channelfaqsearch.xml
#ExecuteCampaign =./profile/executecampaign.json

#文件置于与项目同级的目录下
channelfaqsearch=./responseprofile/channelfaqsearch.xml
Executecampaign=./responseprofile/executecampaign.json

#文件路径为按绝对路径
#ChannelFaqSearch =/apps/ Responseprofile/channelfaqsearch.xml</span>

The code to convert the <2> XML file to string is as follows:

<span style= "FONT-SIZE:18PX;"

>package Cn.migu.util;
Import org.w3c.dom.Document;

Import org.xml.sax.SAXException;
Import Javax.xml.parsers.DocumentBuilder;
Import Javax.xml.parsers.DocumentBuilderFactory;
Import javax.xml.parsers.ParserConfigurationException;
Import javax.xml.transform.*;
Import Javax.xml.transform.dom.DOMSource;
Import Javax.xml.transform.stream.StreamResult;
Import Java.io.ByteArrayOutputStream;

Import java.io.IOException;  /** * <Description> XmlReader help class * @author Yanlu * */public class Xmlreaderhelper {private static Document

    Document Converts an XML file to String and uses DOM to parse XML public static String Xmlstrreader (String fileName) {try {//Get DOM parser worker
            Factory in order to produce the parser documentbuilderfactory DBF = Documentbuilderfactory.newinstance ();
            
            Gets the DOM parser to parse DOM Documentbuilder db = Dbf.newdocumentbuilder (); Converts the XML document to be parsed into an input stream so that the DOM parser resolves it//inputstream is= new fileinputsTream ("Test1.xml");

            Parse XML document input stream, get a document document = Db.parse (FileName);
            Transformerfactory tf = Transformerfactory.newinstance ();
            Transformer t = Tf.newtransformer ();
            T.setoutputproperty (outputkeys.encoding, "UTF-8");
            Bytearrayoutputstream BOS = new Bytearrayoutputstream ();
            T.transform (new Domsource (document), New Streamresult (BOS));
            String xmlstr = bos.tostring ();
        return xmlstr;
        catch (Parserconfigurationexception e) {System.err.println (E.getmessage ());
        catch (Saxexception e) {System.err.println (E.getmessage ());
        catch (IOException e) {System.err.println (E.getmessage ());
        catch (Transformerconfigurationexception e) {System.err.println (E.getmessage ());
        catch (Transformerexception e) {System.err.println (E.getmessage ()); } return Null; }} </span>

<3> JSON file Conversion string code is as follows:

<span style= "FONT-SIZE:18PX;"

>package Cn.migu.util;

Import java.io.*; /** * <Description> Read file method encapsulation * @author Yanlu * */public class Fileutil {/** * read. json file method * @param filep
        ATH * @return/public static string ReadFile (String filePath) {BufferedReader reader=null;
        StringBuilder Result=null;
            try {fileinputstream instream=new fileinputstream (FilePath);
            InputStreamReader inreader=new InputStreamReader (instream, "UTF-8");
            Reader=new BufferedReader (Inreader);
            Result=new StringBuilder ();
            String TempStr;
            while ((Tempstr=reader.readline ())!=null) {result.append (TEMPSTR);
        } reader.close ();
        catch (FileNotFoundException e) {e.printstacktrace ();
        catch (Unsupportedencodingexception e) {e.printstacktrace ();
        catch (IOException e) {e.printstacktrace (); }finAlly {if (reader!=null) {try {reader.close ();
                catch (IOException e) {e.printstacktrace ();
    }} return result.tostring (); }} </span>


<4> output Response message code is as follows:

<span style= "FONT-SIZE:18PX;"

>package Cn.migu.util;

Import Org.eclipse.jetty.server.Request;
Import java.io.IOException;

Import Java.io.PrintWriter;

Import Javax.servlet.http.HttpServletResponse; 
	 /** * <Description> Response Output Flow tool class sample, customizable * * @author Yanlu * */public class Outprinterutil {/** * response XML format string  * @param response * @param result * @throws ioexception/public static void Outputxml (HttpServletResponse
		Response, StringBuilder result) throws IOException {//Response.setcontenttype ("Application/xml");
		Response.setcharacterencoding ("UTF-8");
		Response.setstatus (HTTPSERVLETRESPONSE.SC_OK);
		SYSTEM.ERR.PRINTLN ("Response code is:" +HTTPSERVLETRESPONSE.SC_OK);
		PrintWriter pw = Response.getwriter ();
		Pw.print (Result.tostring ());
		Pw.flush ();
	Pw.close (); /** * Response to JSON format string * * @param JSON * @param response/public static void Outputjson (string json, Httpserv
	Letresponse response) {try {response.setcharacterencoding ("UTF-8");		The JSON string must be in JSON format, otherwise there will be an error Response.setcontenttype ("Application/json");
			Prevent buffering Response.setdateheader ("Expires", 0) on proxy server side;
			PrintWriter out = Response.getwriter ();
			Out.print (JSON);
			Out.flush ();
		Out.close ();
		catch (Exception e) {e.printstacktrace (); }/** * Results that need to be returned to the user do not support session * * @param baserequest * @param response * @param result * @throws ioexcept Ion */public static void Outputnosession (Request baserequest, httpservletresponse response, String result) throws I
		oexception {response.setcontenttype ("text/json;charset=utf-8");
		Response.setstatus (HTTPSERVLETRESPONSE.SC_OK);
		Baserequest.sethandled (TRUE);
	Response.getwriter (). println (result);
	 }/* Private Outprinterutil () {super ();} */} </span>


3. Test pile run. Take Httpserverdemo as an example, start the Httpserverdemo.java Main method, and enter the request path configured in the main method in the browser http://localhost:19993/test/ Channelfaqsearch (I run the computer, IP for localhost, layout to the server, replace the server IP), you can see the message returned.


4. Note the point

Pack and run on the server, and note the selection of the main function (choose the Java class for the port you want to start).

Take the Eclipse Jar pack as an example, as follows:

Right-click the test pile Project--> Export-->



Click Next


Click Finish to complete

Then upload the packed jar package (such as Jettyserver.jar) to the server

You can command to run the JAR package (first assign permissions to the jar file, or you may not be able to execute it).

Example: The order is as follows: Java-jar Jettyserver.jar

Second, test pile server Deployment 1 Deployment Test Pile Environment

1>. When the test pile is completed, it is called a jar package, the relevant port number defined in the package, and the request path of the test pile are confirmed.

2> Modify the address of the interface in the configuration file to the corresponding test pile (IP is the host IP of the server where the jar package resides, and the port is the defined port)

3> Deploy the jar package to the server (I am currently building a directory on the 192.168.129.145 server as a storage path for test piles:/apps/stub_test/Everyone can place the jar package here, of course, it can be customized) 2 Start off Test pile

Linux start Test pile command:

1>. #java-jar Teststub.jar &

This command indicates that the jar package is started

Note: Add & Show Process to run in background

2> #jobs

To view a list of tasks that run in the background

3>. #nohup Java-jar Teststub.jar &

If you want to quit the terminal after the service does not terminate the use of the Nohup command, Nohup is to quit the terminal, the program will not end, use the Nohup command should be aware that the service will not stop, you should pay attention to the process to kill

If the following message appears, not an error, it indicates that the program running information will be output to the Nohup.out

#nohup: Ignoring input and appending output to ' nohup.out '

4> #jobs-L

Show the process number of the service as shown in the figure

#kill-9 Process number

Kill the process.

3 points to note

1>. When using a test pile, the return message is placed externally for reading as an XML (or JSON) file, which makes it easy to test more scenarios when testing by modifying an XML file

2> If you are wrong in the start Jar package times, notice if the port number is occupied


#知识传送门:

Https://github.com/russ44/easyMock

These are the mock platforms I wrote for testing piles, which are simple to understand, and can be run directly by playing the project as a war package and deploying a Tomcat container.

The platform can be used as a lightweight mock platform through the foreground Web page management interface.

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.