Showing posts with label Web Service Testing. Show all posts
Showing posts with label Web Service Testing. Show all posts

Monday, September 29, 2014

Web Service Testing Example



package testingWS;

import groovyx.net.http.ContentType;

import org.junit.Before;
import org.junit.Test;

import com.jayway.restassured.RestAssured;
import com.jayway.restassured.path.json.JsonPath;
import com.jayway.restassured.response.Response;

import static com.jayway.restassured.RestAssured.expect;
import static com.jayway.restassured.RestAssured.get;
import static com.jayway.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.*;


public class TestingUsingRestAssured {

 @Before
   public void setUp(){
    //  do something
   }



@Test
public void testUserFetchesSuccess() {
expect().
body("id", equalTo(12)).
body("firstName", equalTo("Tim")).
body("lastName", equalTo("Tester")).
when().
get("/abc/users/id/12");
}


@Test
   public void testGetProducts(){
       expect().statusCode(200).contentType(ContentType.JSON)
       .when().get("/abc/users/id/1");
   }



// testing a simple response containing some JSON data
@Test
public void testGetSingleUser() {
 expect().
   statusCode(200).
   body(
     "firstName", equalTo("Tim"),
     "lastName", equalTo("Testerman"),
     "id", equalTo(1)).
   when().
   get("/abc/users/single-user");
}

@Test
public void testGetSingleUse1r() {
given().
pathParam("id",1).
expect().
statusCode(200).
body("id", equalTo(1),
"firstName", equalTo("Tim")).

when().
get("/abc/users/id");
}




//we’re using JsonPath to programatically test the returned JSON structure we’re
//using JsonPath to programatically test the returned JSON structure
@Test
public void testGetSingleUserProgrammatic() {

  Response res = get("/abc/users/single-user");

  assertEquals(200, res.getStatusCode());

  String json = res.asString();
  JsonPath jp = new JsonPath(json);

  assertEquals("Tim", jp.get("firstName"));
  assertEquals("Testerman", jp.get("lastName"));
  assertEquals(1, jp.get("id"));
}







// handling basic authentication
// Response Status: 401 Unauthorized/ 200 Status Ok (when logged in with username=admin and password=admin)
/* @Test
public void testAuthenticationWorking() {
  // we're not authenticated, service returns "401 Unauthorized"
  expect().
    statusCode(401).
  when().
  get("/abc/users/secure/person");
  // with authentication it is working
  expect().
    statusCode(200).
  when().
    with().
      authentication().basic("admin", "admin").
  get("/abc/users/secure/person");
}*/


/* @Test
public void testCreateuser() {
  final String firstName = "Tim";
  final String lastName = "Tester";

  given().
    parameters(
      "firstName", firstName,
      "lastName", lastName).
  expect().
    body("firstName", equalTo(firstName)).
    body("lastName", equalTo(lastName)).
  when().
  get("/abc/users/create");
}*/

}

Example 10



package testingWS;

import static org.junit.Assert.assertEquals;


import org.junit.Test;

import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.test.framework.AppDescriptor;
import com.sun.jersey.test.framework.JerseyTest;
import com.sun.jersey.test.framework.WebAppDescriptor;
//jettison reads and writes json
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;


public class TestingUsingJerseyTestFrameWork extends JerseyTest {

@Override
protected AppDescriptor configure() {
// traffic logging
// enable(TestProperties.LOG_TRAFFIC);
//If set to true the property enables basic logging of the request and response flow on both - client and server
return new WebAppDescriptor.Builder().build();
}

 @Test
public void testUser() throws JSONException{
 WebResource webResource = client().resource("http://localhost:8080/");
 JSONObject json =webResource.path("/abc/users/id/12") .get(JSONObject.class);

// String jsonStringObj = json.toString();
 //String jsonStringObj = json.toString();
//  Gson gson = new Gson();
/*  User obj = gson.fromJson(jsonStringObj, User.class);*/

 assertEquals(12,json.get("id"));
 assertEquals("Tim", json.get("firstName"));
 assertEquals("Tester", json.get("lastName"));

 }

 @Test
 public void testTrack() throws JSONException{
 WebResource webResource = client().resource("http://localhost:8080/");
 JSONObject json =webResource.path("/abc/users/get").get(JSONObject.class);
 //String jsonStringObj = json.toString();
/*  Gson gson = new Gson();
 User obj = gson.fromJson(jsonStringObj, User.class);*/

 assertEquals("Mr. Big",json.get("singer"));
 assertEquals("Wild World", json.get("title"));
 }


}

Example



 package testingWS;

 import org.junit.Test;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

public class TestingUsingJerseyClient {

@Test
public void testgetUsingJerseyClient(){
Client client = Client.create();
WebResource webResource = client
  .resource("http://localhost:8080/abcrAuthorization/api/authz");
ClientResponse response = webResource.accept("application/json")
                   .get(ClientResponse.class);


if (response.getStatus() != 200) {
  throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}

String output = response.getEntity(String.class);
System.out.println("Output from Server .... \n");
System.out.println("Output from Server .... \n"+output);
}

@Test
public void testpostUsingJerseyClient(){
Client client = Client.create();
WebResource webResource = client
  .resource("http://localhost:8080/abc/users/post");
String input = "{\"singer\":\"Mr. Big\",\"title\":\"Wild World\"}";
ClientResponse response = webResource.type("application/json")
  .post(ClientResponse.class, input);
if (response.getStatus() != 201) {
throw new RuntimeException("Failed : HTTP error code : "
    + response.getStatus());
}
String output = response.getEntity(String.class);

}

}

Sample 8



package testingWS;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import First.Track;
import First.User;
import First.UserWebService;
import Service.TrackService;
import Service.UserService;


public class TestingDuringDevelopment {

@Mock
private UserService userService;

@Mock TrackService trackService;

@InjectMocks
private UserWebService userWebServiceMock=new UserWebService();


@Before
public void testBefore() {
MockitoAnnotations.initMocks(this);
User user = new User();
user.setId(12);
user.setFirstName("Tim");
user.setLastName("Tester");
when(userService.getUser(12)).thenReturn(user);

Track track = new Track();
track.setTitle("AWMAWY");
track.setSinger("Joe Satriani");
when(trackService.getTrack()).thenReturn(track);
}

@Test
public void testTrack(){
Track track= userWebServiceMock.getTrackInJSON();
Track newTrack=new Track();
newTrack.setSinger("Joe Satriani");
newTrack.setTitle("AWMAWY");
assertEquals(track.getSinger(), newTrack.getSinger());
assertEquals(track.getTitle(), newTrack.getTitle());
verify(trackService);

}


}

Sample 7

package FrameworkWrapper;


import javax.net.ssl.HttpsURLConnection;
import java.net.HttpURLConnection;
import java.net.URLConnection;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Scanner;

public class SimpleRestClient {

    public Response doGetRequest(URL url, HashMap<String,String> headers, HashMap<String,String> params, boolean debug) {
        GET get = new GET(url, headers, params);
        return sendRequest(get, debug);
    }

    public Response doPostRequest(URL url, HashMap<String,String> headers, String body, boolean debug) {
        POST post = new POST(url, headers, body);
        return sendRequest(post, debug);
    }

    private Response sendRequest(Request request, boolean debug) {
        HttpURLConnection conn = null;
        Response response = null;
        long time = 0;

        try {
            conn = (HttpURLConnection) request.getUrl().openConnection();

            if (request.headers != null) {
                for (String header : request.headers.keySet()) {
                    conn.addRequestProperty(header, request.headers.get(header));
                }
            }

            time = System.currentTimeMillis();          

            if (request instanceof POST) {
                byte[] payload = ((POST)request).body.getBytes();

                conn.setDoOutput(true);
                conn.setFixedLengthStreamingMode(payload.length);
                conn.getOutputStream().write(payload);
            }

            int status = conn.getResponseCode();

            if(status != HttpURLConnection.HTTP_OK)
                response = new Response(status, conn.getResponseMessage());
            else
                response = new Response(status, readInputStream(conn.getInputStream()));

            response.time = System.currentTimeMillis() - time;
            if(debug) dumpRequest(request, response);

        } catch (IOException e) {
            e.printStackTrace(System.err);

        } finally {
            if (conn != null)
                conn.disconnect();
        }

        return response;
    }

    private static String readInputStream(InputStream is) throws IOException {
        Scanner s = new Scanner(is, "UTF-8").useDelimiter("\\A");
        return s.hasNext() ? s.next() : "";
    }

    /**
     * Convenience method to output everything about the request
     */
    public void dumpRequest(Request req, Response resp)
            throws MalformedURLException {
        StringBuilder sb = new StringBuilder();
        sb.append("=> Dumping request information:");
        sb.append("\n").append("======================= REQUEST ==========================");
        sb.append("\n==> ").append("URL: ").append(req.getUrl());
        sb.append("\n==> ").append("Method: ").append((req instanceof POST ? "POST" : "GET"));

        if(req.headers != null) {
            for(String header : req.headers.keySet())
                sb.append("\n===> ").append("Header: ").append(header).append(": ").append(req.headers.get(header));
        }

        if(req instanceof GET && ((GET)req).params != null){
            for(String param : ((GET)req).params.keySet())
                sb.append("\n===> ").append("Param: ").append(param).append("=").append(((GET)req).params.get(param));
        }

        if(req instanceof POST)
            sb.append("\n==> ").append("Request body: ").append(((POST)req).body);

        sb.append("\n").append("======================= RESPONSE =========================");

        sb.append("\n==> ").append("Round trip time: ").append(resp.time).append(" ms");
        sb.append("\n==> ").append("Response status: ").append(resp.status);      
        sb.append("\n==> ").append("Response body:\n").append(resp.body);      

        sb.append("\n==========================================================");

        System.out.println(sb.toString());
    }


    private class Request {
        public URL baseUrl;
        public HashMap<String,String> headers;

        public Request(URL baseUrl, HashMap<String,String> headers) {
            this.baseUrl = baseUrl;
            this.headers = headers;
        }

        public URL getUrl() throws MalformedURLException{
            return baseUrl;
        }
    }

    private class POST extends Request {
        public String body;

        public POST(URL baseUrl, HashMap<String,String> headers, String body){
            super(baseUrl, headers);
            this.body = body;
        }
    }

    private class GET extends Request {
        public HashMap<String,String> params;

        public GET(URL baseUrl, HashMap<String,String> headers, HashMap<String,String> params){
            super(baseUrl, headers);
            this.params = params;
        }

        @Override
        public URL getUrl() throws MalformedURLException {
            StringBuilder sb = new StringBuilder(baseUrl.toString());
            if(params != null && params.size() > 0)
                sb.append(createParamString());

            return new URL(sb.toString());
        }

        private String createParamString() {
            StringBuilder sb = new StringBuilder();
            if(params != null && params.size() > 0) {
                sb.append("?");
                //TODO: Need to encode the paramater values
                for (String param : params.keySet()) {
                    sb.append(param).append("=").append(params.get(param)).append("&");
                }
                sb.deleteCharAt(sb.length()-1);          
            }
            return sb.toString();
        }
    }

    public class Response {
        public int status;
        public String body;
        public long time;

        protected Response(int status, String body) {
            this.status = status;
            this.body = body;
        }
    }
}

Sample 6

package FrameworkWrapper;

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ServletResponse extends HttpServlet
{

   public void doGet (HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
   {

      Enumeration keys;
      String key;
      String myName = "";
      keys = request.getParameterNames();
      while (keys.hasMoreElements())
      {
         key = (String) keys.nextElement();
         if (key.equalsIgnoreCase("myName")) myName = request.getParameter(key);
      }
      System.out.println("Name = ");
      if (myName == "") myName = "Hello";

      response.setContentType("text/html");
      response.setHeader("Pragma", "No-cache");
      response.setDateHeader("Expires", 0);
      response.setHeader("Cache-Control", "no-cache");

      PrintWriter out = response.getWriter();
      out.println("json object");
   
      out.flush();
     
   // ---------------- Note:One approach--------------------------
      //response.setContentType("application/json");
   // Get the printwriter object from response to write the required json object to the output stream    
  // PrintWriter out = response.getWriter();
   // Assuming your json object is **jsonObject**, perform the following, it will return your json object
   //out.print(jsonObject);
   //out.flush();
     
      // ---------------- Note:One approach--------------------------
     
//      JSONObject json      = new JSONObject();
//      JSONArray  addresses = new JSONArray();
//      JSONObject address;
//      try
//      {
//         int count = 15;
//
//         for (int i=0 ; i<count ; i++)
//         {
//             address = new JSONObject();
//             address.put("CustomerName"     , "Decepticons" + i);
//             address.put("AccountId"        , "1999" + i);
//             address.put("SiteId"           , "1888" + i);
//             address.put("Number"            , "7" + i);
//             address.put("Building"          , "StarScream Skyscraper" + i);
//             address.put("Street"            , "Devestator Avenue" + i);
//             address.put("City"              , "Megatron City" + i);
//             address.put("ZipCode"          , "ZZ00 XX1" + i);
//             address.put("Country"           , "CyberTron" + i);
//             addresses.add(address);
//         }
//         json.put("Addresses", addresses);
//      }
//      catch (JSONException jse)
//      {
//
//      }
//      response.setContentType("application/json");
//      response.getWriter().write(json.toString());
     
      // ---------------- Note:One approach--------------------------
     
//      /**
//       * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
//       */
//      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//
//          request.setCharacterEncoding("utf8");
//          response.setCharacterEncoding("utf8");
//          response.setContentType("application/json");
//          PrintWriter out = response.getWriter();
//          JSONObject jsonObj = (JSONObject) JSONValue.parse(request.getParameter("para"));
//          System.out.println(jsonObj.get("message"));        
//          JSONObject obj = new JSONObject();
//          obj.put("message", "hello from server");
//          out.print(obj);
//
//      }

   

   }
}

Sample 5

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import com.howtodoinjava.model.User;

public class PureJavaClient
{
    public static void main(String[] args)
    {
        try
        {
            URL url = new URL("http://localhost:8080/RESTfulDemoApplication/user-management/users/10");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept", "application/xml");

            if (conn.getResponseCode() != 200)
            {
                throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
            }

            BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
            String apiOutput = br.readLine();
            System.out.println(apiOutput);
            conn.disconnect();
 // this part need to be repalce with json parser
            JAXBContext jaxbContext = JAXBContext.newInstance(User.class);
            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            User user = (User) jaxbUnmarshaller.unmarshal(new StringReader(apiOutput));

            System.out.println(user.getId());
            System.out.println(user.getFirstName());
            System.out.println(user.getLastName());
           
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }
}

Sample 4

package FrameworkWrapper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class NetClientPost {

// http://localhost:8080/RESTfulExample/json/product/post
public static void main(String[] args) {

 try {

URL url = new URL("http://localhost:8080/RESTfulExample/json/product/post");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");

String input = "{\"qty\":100,\"name\":\"iPad 4\"}";

OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();

if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}

BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));

String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}

conn.disconnect();

 } catch (MalformedURLException e) {

e.printStackTrace();

 } catch (IOException e) {

e.printStackTrace();

}

}

}

Sample 3

package FrameworkWrapper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class NetClientGet {

// http://localhost:8080/RESTfulExample/json/product/get
public static void main(String[] args) {

 try {

URL url = new URL("http://localhost:8080/RESTfulExample/json/product/get");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");

if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}

BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));

String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}

conn.disconnect();

 } catch (MalformedURLException e) {

e.printStackTrace();

 } catch (IOException e) {

e.printStackTrace();

 }

}

}

Sample 2

package FrameworkWrapper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class JavaNetURLRESTFulClientPost {

private static final String targetURL = "http://localhost:8080/JerseyJSONExample/rest/jsonServices/send";

public static void main(String[] args) {

try {

URL targetUrl = new URL(targetURL);

HttpURLConnection httpConnection = (HttpURLConnection) targetUrl.openConnection();
httpConnection.setDoOutput(true);
httpConnection.setRequestMethod("POST");
httpConnection.setRequestProperty("Content-Type", "application/json");

String input = "{\"id\":1,\"firstName\":\"Liam\",\"age\":22,\"lastName\":\"Marco\"}";

OutputStream outputStream = httpConnection.getOutputStream();
outputStream.write(input.getBytes());
outputStream.flush();

if (httpConnection.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ httpConnection.getResponseCode());
}

BufferedReader responseBuffer = new BufferedReader(new InputStreamReader(
(httpConnection.getInputStream())));

String output;
System.out.println("Output from Server:\n");
while ((output = responseBuffer.readLine()) != null) {
System.out.println(output);
}

httpConnection.disconnect();

 } catch (MalformedURLException e) {

e.printStackTrace();

 } catch (IOException e) {

e.printStackTrace();

}

}
}

Sample 1

package FrameworkWrapper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class JavaNetURLRESTFulClientGet {

private static final String targetURL = "http://localhost:8080/JerseyJSONExample/rest/jsonServices/print";

public static void main(String[] args) {

 try {

URL restServiceURL = new URL(targetURL);

HttpURLConnection httpConnection = (HttpURLConnection) restServiceURL.openConnection();
httpConnection.setRequestMethod("GET");
httpConnection.setRequestProperty("Accept", "application/json");

if (httpConnection.getResponseCode() != 200) {
throw new RuntimeException("HTTP GET Request Failed with Error code : "
+ httpConnection.getResponseCode());
}

BufferedReader responseBuffer = new BufferedReader(new InputStreamReader(
(httpConnection.getInputStream())));

String output;
System.out.println("Output from Server:  \n");

while ((output = responseBuffer.readLine()) != null) {
System.out.println(output);
}

httpConnection.disconnect();

 } catch (MalformedURLException e) {

e.printStackTrace();

 } catch (IOException e) {

e.printStackTrace();

 }

}
}