Interface Automation test framework build –java+testng Test restful service

Source: Internet
Author: User
Tags getmessage testng

Interface Automation Test –java+testng testing Restful Web Service

Keywords: rest-based Web services, interface Automation testing, data-driven testing, testing restful WEB service, data separation, java+maven+testng

This article mainly describes how to use Java for RESTful Web service to do interface Automation testing (data-driven), compared to UI Automation, interface automation stability, high reliability, low degree of implementation, automation cost-effective. The tool or class library used is TestNG, Apache POI, Jayway Rest-assured,skyscreamer-jsonassert

Brief introduction:

The idea is data-driven testing, which uses Excel to manage the data, the input data is stored in the Sheet, the data is read, the request is called service, and the response is written to ' Output ' Sheet The actual result, ' Baseline ' is the baseline (expected result) used to compare with the actual results, the ' Comparison ' Sheet is a record of inconsistent results, ' result ' Sheet is a simple result report.

MAVEN Project directory structure:

Detailed Introduction

The core is a test class Httpreqgentest.java consists of four parts

@BeforeTest read ' Input ' and ' Baseline ' sheet of Excel (WorkBook)

and create a new ' Output ', ' Comparison ', ' Result ' three empty sheet

Read Http_request_template.txt content into string

@DataProvider (name = "Workbookdata")

TestNG Dataprovider, first use DataReader constructor, read the data of input in Excel, put in hashmap<string, Recordhandler> The key value of the map is test The id,value of the case is the Recordhandler object, an important member property of this object is the key-value pair of column and value in input sheet, and the Traverse map will test the case ID with the value of the test case That is, the value of the first two columns of input sheet is placed in list<object[]>, and finally the iterator iterator of the list is returned (in order to invoke the @test method)

@Test (Dataprovider = "Workbookdata", description = "Reqgentest")

The test method, which is provided by Dataprovider, first takes the Recordhandler in Myinputdata by ID, generates the request by it and the template, and then executes the request return response. All of this work is done by the Httpreqgen.java class, and with Com.jayway.restassured, the returned response is a JSON body, Compare with pre-filled expected results (also JSON format) in Org.skyscreamer.jsonassert.JSONCompare and baseline, depending on whether the result is pass or fail, will write the result accordingly to the corresponding sheet in Excel.

@AfterTest

Write some data for statistics

Close file stream

Implementation code:

Httpreqgentest.java

Package Com.demo.qa.rest_api_test;import Java.io.fileinputstream;import Java.io.filenotfoundexception;import Java.io.fileoutputstream;import Java.io.ioexception;import Java.io.inputstream;import Java.nio.charset.Charset; Import Java.text.simpledateformat;import java.util.arraylist;import java.util.date;import java.util.Iterator; Import Java.util.list;import Java.util.map;import Org.apache.commons.io.ioutils;import Org.apache.poi.xssf.usermodel.xssfsheet;import Org.apache.poi.xssf.usermodel.xssfworkbook;import Org.json.jsonexception;import Org.skyscreamer.jsonassert.jsoncompare;import Org.skyscreamer.jsonassert.jsoncomparemode;import Org.skyscreamer.jsonassert.jsoncompareresult;import Org.testng.assert;import Org.testng.itest;import Org.testng.itestcontext;import org.testng.annotations.AfterTest; Import Org.testng.annotations.beforetest;import Org.testng.annotations.dataprovider;import Org.testng.annotations.parameters;import Org.testng.annotations.test;import Com.demo.qa.utils.DataReader;Import Com.demo.qa.utils.datawriter;import Com.demo.qa.utils.httpreqgen;import Com.demo.qa.utils.RecordHandler; Import Com.demo.qa.utils.sheetutils;import Com.demo.qa.utils.utils;import    Com.jayway.restassured.response.response;public class Httpreqgentest implements ITest {private response response;    Private DataReader Myinputdata;    Private DataReader Mybaselinedata;    private String template;    Public String Gettestname () {return "API Test";        } String FilePath = "";    Xssfworkbook wb = null;    Xssfsheet inputsheet = null;    Xssfsheet baselinesheet = null;    Xssfsheet outputsheet = null;    Xssfsheet comparsionsheet = null;        Xssfsheet resultsheet = null;    Private double totalcase = 0;    Private double failedcase = 0;    Private String StartTime = "";        Private String EndTime = "";        @BeforeTest @Parameters ("WorkBook") public void Setup (String path) {filePath = path; try {wb = new Xssfworkbook (New FileInputStream (FilePath));        } catch (FileNotFoundException e) {e.printstacktrace ();        } catch (IOException e) {e.printstacktrace ();        } Inputsheet = Wb.getsheet ("Input");        Baselinesheet = Wb.getsheet ("Baseline");        Sheetutils.removesheetbyname (WB, "Output");        Sheetutils.removesheetbyname (WB, "Comparison");        Sheetutils.removesheetbyname (WB, "Result");        Outputsheet = Wb.createsheet ("Output");        Comparsionsheet = Wb.createsheet ("Comparison");        Resultsheet = Wb.createsheet ("Result");            try {InputStream is = HTTPReqGenTest.class.getClassLoader (). getResourceAsStream ("Http_request_template.txt");        Template = Ioutils.tostring (is, Charset.defaultcharset ());        } catch (Exception e) {assert.fail ("problem fetching data from input file:" + e.getmessage ());        } SimpleDateFormat sf=new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); StartTime = Sf.format (New DAte ());        } @DataProvider (name = "Workbookdata") protected iterator<object[]> Testprovider (Itestcontext context) {            list<object[]> test_ids = new arraylist<object[]> ();            Myinputdata = new DataReader (Inputsheet, True, true, 0);            map<string, recordhandler> myinput = Myinputdata.get_map (); Sort map In order so the test cases ran in a fixed order map<string, recordhandler> sortmap = UTILS.S                        Ortmap (Myinput);                For (map.entry<string, recordhandler> entry:sortmap.entrySet ()) {String test_id = Entry.getkey ();                String test_case = Entry.getvalue (). Get ("TestCase"); if (!test_id.equals ("") &&!test_case.equals ("")) {Test_ids.add (new object[] {test_id, test_c                ASE});            } totalcase++;    } mybaselinedata = new DataReader (Baselinesheet, True, true, 0);    return Test_ids.iterator ();  } @Test (Dataprovider = "Workbookdata", description = "reqgentest") public void Api_test (string ID, String test_case)        {Httpreqgen Myreqgen = new Httpreqgen ();            try {myreqgen.generate_request (template, Myinputdata.get_record (ID));        Response = Myreqgen.perform_request (); } catch (Exception e) {assert.fail ("problem using Httprequestgenerator to generate response:" + e.getmessage (        ));        } String baseline_message = Mybaselinedata.get_record (ID). Get ("Response"); if (response.statuscode () = =) try {datawriter.writedata (Outputsheet, response.asstring (), I                                D, test_case); Jsoncompareresult result = Jsoncompare.comparejson (Baseline_message, response.asstring (), Jsoncomparemode.non_                extensible);       if (!result.passed ()) {Datawriter.writedata (Comparsionsheet, result, ID, test_case);             Datawriter.writedata (Resultsheet, "false", ID, Test_case, 0);                    Datawriter.writedata (Outputsheet);                failedcase++;                } else {datawriter.writedata (Resultsheet, "true", ID, Test_case, 0); }} catch (Jsonexception e) {datawriter.writedata (Comparsionsheet, "", "problem to assert RESPO                NSE and baseline messages: "+e.getmessage (), ID, test_case);                Datawriter.writedata (Resultsheet, "error", ID, Test_case, 0);                failedcase++;            Assert.fail ("Problem to assert Response and baseline messages:" + e.getmessage ());            } else {datawriter.writedata (Outputsheet, Response.statusline (), ID, test_case); if (Baseline_message.equals (Response.statusline ())) {Datawriter.writedata (Resultsheet, "true", ID, Test_ca            SE, 0); } else {datawriter.writedata (Comparsionsheet, BaseliNe_message, Response.statusline (), ID, test_case);                Datawriter.writedata (Resultsheet, "false", ID, Test_case, 0);                Datawriter.writedata (Outputsheet);            failedcase++; }}} @AfterTest public void teardown () {SimpleDateFormat sf=new SimpleDateFormat ("Yyyy-mm-dd hh:m        M:ss ");        EndTime = Sf.format (New Date ());                Datawriter.writedata (Resultsheet, Totalcase, Failedcase, StartTime, endTime);            try {fileoutputstream FileOutputStream = new FileOutputStream (FilePath);            Wb.write (FileOutputStream);        Fileoutputstream.close ();        } catch (FileNotFoundException e) {e.printstacktrace ();        } catch (IOException e) {e.printstacktrace (); }    }}

DataReader

View Code

Httpreqgen

View Code

Recordhandler

View Code

Other unimportant classes are not listed.

Pom.xml

View Pom.xml

Run is performed through the testng XML file, which is configured with the parameter "WorkBook" path

TestNG running results are pass, but in fact there is a case is fail, I just use testng to run, I did not in the @test method add assert assert, so here will not fail, My goal is to fully use Excel to manage maintenance test data and test results, so that the data scripts are completely detached.

Output Sheet

Comparison Sheet

Result Sheet

Of course you can also run the MAVEN project as an executable jar, but you need to add a main function as a portal, the XML test file is passed through the parameters, and you need to configure some plugins in the Pom, like Maven-jar-plugin.

If you still need to do back-end DB check, you can add a few more columns in input, you want to query the table, field, baseline also corresponding to the desired results, here will not repeat.

Http://www.cnblogs.com/wade-xu/p/4229805.html

NOTE: The reprint must indicate the source and the author name.

Interface Automation test framework build –java+testng Test restful service

Related Article

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.