Search code examples
javarestjerseyjax-rs

Assertion failure when testing POST request with PathSegment in PathParam


I have a REST API POST request that takes multiple entries. These entries are extracted using PathSegment. The API is working but when I write a test case using Rest Assured, I am getting assertion failure. I am using JAX-RS and Jersey for the APIs.

I have gone through SO and some other forums for an answer but nothing satisfactory.

My REST API code is:

  @Produces(MediaType.APPLICATION_JSON)
  @Path("/order/{id}/{var1: items}/{var2: qty}")
  public final String orderMultipleItems(@PathParam("var1") final PathSegment itemPs, @PathParam("var2") final PathSegment qtyPs,
      @PathParam("id") final int id) {
    HashMap<Integer, Integer> items = new HashMap<Integer, Integer>();

    //rest of the code
}

This is my rest assured code:

@Test
  public final void testOrderMultipleItems() throws URISyntaxException, AssertionError {
    String msg= given().contentType("application/json").when()
        .post(TestUtil.getURI("/api/customer/order/1002/items;item=3006;item=3005/qty;q=1;q=1"))
        .getBody().asString();
    assertNotEquals("Order(s) Received", msg);
  }

I am getting a 404 when testing but 200 when I run the POST request through curl. Am I making a mistake in the test case for my post request?

Any suggestion would be appreciated.


Solution

  • When you send a request URI to the server using curl it submits as it is:

    http://localhost/api/customer/order/1002/items;item=3006;item=3005/qty;q=1;q=1
    

    But, when you send URI through RestAssured (using post), RestAssured encodes special characters ';' to '%3B' and '=' to '%3D' and request URI becomes like this:

    http://localhost/api/customer/order/1002/items%3Bitem%3D3006%3Bitem%3D3005/qty%3Bq%3D1%3Bq%3D1
    

    Which is not understandable to the server. That is the problem.

    So, you can avoid this by using the following code before sending a request,

    RestAssured.urlEncodingEnabled = false;
    

    Hope this solves your problem.