Skip to content

Different File Formats

Roman Jakubco edited this page Jan 11, 2018 · 2 revisions

Prerequisite

Use JSON in Virtualized Response

This service is configured to respond to GET requests that are defined using the forGet(String url) method with a message that contains JSON body as defined by the JSON_EXAMPLES_PORTFOLIO variable. The JSON response is converted to a POJO CaPortfolio class.


Using JSON:

 private static final String URL = "http://www.ca.com/portfolio";

  private static final String JSON_EXAMPLES_PORTFOLIO = "{\n"
      + "  \"productNamesList\": [\n"
      + "    \"CA Server Automation\",\n"
      + "    \"CA Service Catalog\",\n"
      + "    \"CA Service Desk Manager\",\n"
      + "    \"CA Service Management\",\n"
      + "    \"CA Service Operations Insight\",\n"
      + "    \"CA Service Virtualization\"\n"
      + "  ]\n"
      + "}";

  @Rule
  public VirtualServerRule vs = new VirtualServerRule();

  @Test
    public void testVirtualizeJsonResponse() throws IOException {
      forGet(URL).doReturn(
          okMessage()
              .withJsonBody(JSON_EXAMPLES_PORTFOLIO)
      );
  
      HttpGet httpGet = new HttpGet(URL);
      HttpClient httpClient = HttpClientBuilder.create().build();
      HttpResponse httpResponse = httpClient.execute(httpGet);
  
      assertEquals(200, httpResponse.getStatusLine().getStatusCode());
  
      BufferedReader reader = new BufferedReader(
          new InputStreamReader(httpResponse.getEntity().getContent()));
      String inputLine;
      StringBuffer response = new StringBuffer();
  
      while ((inputLine = reader.readLine()) != null) {
        response.append(inputLine);
      }
      reader.close();
  
      Gson gson = new Gson();
  
      CaPortfolio portfolio = gson.fromJson(response.toString(), CaPortfolio.class);
  
      assertNotNull(portfolio);
      assertNotNull(portfolio.getProductNamesList());
      assertTrue(portfolio.getProductNamesList().size() == 6);
      assertTrue(portfolio.getProductNamesList().contains("CA Service Management"));
    }

Use JSONPath

This service is configured to respond to POST requests that are defined using the forPost(String url) method with a JSON body that matches the defined JSONPaths:

  • JSONPath "$.portfolio.id"
    Note: This path must exist in the request body.
  • JSONPath "$.portfolio.year"
    Value: Evaluate to 2017
  • JSONPath "$.portfolio.year"
    Value: Evaluate to a string that contains "17"
  • JSONPath?"$.portfolio.productNamesList"
    Value: Evaluate to JSONArray
    Note: The JSON array must contain "CA Service Management".

You can use predefined methods with only string values, or use predefined matchers for more complex matching.

JsonPath Example:

private static final String RESPONSE = "JSON received!";

  private static final String JSON_EXAMPLES_PORTFOLIO = "{"
      + "\"portfolio\": {\n"
      + "   \"id\": \"1\",\n"
      + "   \"year\": \"2017\",\n"
      + "  \"productNamesList\": [\n"
      + "    \"CA Server Automation\",\n"
      + "    \"CA Service Catalog\",\n"
      + "    \"CA Service Desk Manager\",\n"
      + "    \"CA Service Management\",\n"
      + "    \"CA Service Operations Insight\",\n"
      + "    \"CA Service Virtualization\"\n"
      + "  ]\n"
      + "}}";


  @Test
   public void testJsonPath() throws Exception {
     forPost(URL)
         .matchesBodyPayload(matchesJsonPath("$.portfolio.id"))
         .matchesBodyPayload(matchesJsonPath("$.portfolio.year", "2017"))
         .matchesBodyPayload(matchesJsonPath("$.portfolio.year", contains("17")))
         .matchesBodyPayload(
             matchesJsonPath("$.portfolio.productNamesList", hasItem("CA Service Management")))
         .doReturn(
             okMessage().withStringBody(RESPONSE)
         );
 
     HttpClient client = HttpClientBuilder.create().build();
     HttpPost request = new HttpPost(URL);
 
     StringEntity params = new StringEntity(JSON_EXAMPLES_PORTFOLIO_2);
     request.addHeader("Content-Type", "application/json");
     request.setEntity(params);
 
     HttpResponse response = client.execute(request);
 
     BufferedReader reader = new BufferedReader(
         new InputStreamReader(response.getEntity().getContent()));
     StringBuffer result = new StringBuffer();
     String line;
     while ((line = reader.readLine()) != null) {
       result.append(line);
     }
 
     String body = result.toString();
 
     assertEquals(200, response.getStatusLine().getStatusCode());
     assertNotNull(body);
     assertEquals(RESPONSE, body);
   }
  

For a complete JSON example see: JsonExample

For the POJO class click here.

Using XML in Virtualized Response

This service is configured to respond to GET requests that are defined using the forGet(String url) method with a message that contains XML body as defined by the XML_BODY variable. The XML response is converted to a XML Document.

Using XML:

  private static final String URL = "http://www.ca.com/portfolio/xml";

  private static final String XML_BODY = "<portfolio>\n"
      + "    <id>1</id>\n"
      + "    <year>2016</year>\n"
      + "    <productNameList>\n"
      + "      <name>CA Server Automation</name>\n"
      + "      <name>CA Service Catalog</name>\n"
      + "      <name>CA Service Desk Manager</name>\n"
      + "      <name>CA Service Management</name>\n"
      + "      <name>CA Service Operations Insight</name>\n"
      + "      <name>CA Service Virtualization</name>\n"
      + "    </productNameList>\n"
      + "  </portfolio>";

  @Rule
  public VirtualServerRule vs = new VirtualServerRule();

  @Test
  public void testVirtualizedXmlBody() throws IOException, ParserConfigurationException, SAXException {
    HttpFluentInterface.forGet(URL)
        .doReturn(
            okMessage()
                .withXmlBody(XML_BODY)
        );

    HttpClient client = HttpClientBuilder.create().build();
    HttpGet request = new HttpGet(URL);

    HttpResponse response = client.execute(request);

    BufferedReader reader = new BufferedReader(
        new InputStreamReader(response.getEntity().getContent()));
    StringBuffer result = new StringBuffer();
    String line;
    while ((line = reader.readLine()) != null) {
      result.append(line);
    }

    String body = result.toString().replaceAll("\\s+", "");

    assertEquals(200, response.getStatusLine().getStatusCode());
    assertNotNull(body);
    assertEquals(XML_BODY.replaceAll("\\s+", ""), body);

    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();

    InputSource is = new InputSource(new StringReader(XML_BODY));
    Document doc = dBuilder.parse(is);

    doc.getDocumentElement().normalize();

    assertEquals("portfolio", doc.getDocumentElement().getNodeName());

  }

Using XPath

This service is configured to response to POST requests that are defined using the forPost(String url) method with a XML body that matches the defined XPaths:

  • XPath "/portfolio"
    Note: This path must exist in the request body.
  • XPath "/portfolio/year"
    Value: Evaluate to a string that contains "17"
  • XPath "/portfolio/id"
    Value: Evaluate to 2017

As you can see, you can use predefined methods with only string values, or use predefined matchers for more complex matching.

Using XPath:

private static final String URL = "http://www.ca.com/portfolio/xml";

private static final String XML_BODY = "<portfolio>\n"
      + "    <id>1</id>\n"
      + "    <year>2016</year>\n"
      + "    <productNameList>\n"
      + "      <name>CA Server Automation</name>\n"
      + "      <name>CA Service Catalog</name>\n"
      + "      <name>CA Service Desk Manager</name>\n"
      + "      <name>CA Service Management</name>\n"
      + "      <name>CA Service Operations Insight</name>\n"
      + "      <name>CA Service Virtualization</name>\n"
      + "    </productNameList>\n"
      + "  </portfolio>";

  @Rule
  public VirtualServerRule vs = new VirtualServerRule();
  
  @Test
  public void testXmlPath() throws Exception {
    HttpFluentInterface.forPost(URL)
        .matchesBodyPayload(matchesXPath("/portfolio"))
        .matchesBodyPayload(matchesXPath("/portfolio/year", contains("16")))
        .matchesBodyPayload(matchesXPath("/portfolio/id", "1"))
        .doReturn(
            okMessage()
        );

    HttpClient client = HttpClientBuilder.create().build();
    HttpPost request = new HttpPost(URL);

    request.setEntity(new StringEntity(XML_BODY));

    HttpResponse response;
    response = client.execute(request);

    assertEquals(200, response.getStatusLine().getStatusCode());
  }

For a complete example see: XmlExample

Clone this wiki locally