Testing RESTful Web Services made easy using the REST-assured Framework

October 23rd, 2011 by

REST-assured Integration Test Tutorial Logo There are many frameworks out there to facilitate testing RESTful webservices but there is one framework I’d like to acquaint you with my favourite framework named REST-assured.

REST-assured offers a bunch of nice features like a DSL-like syntax, XPath-Validation, Specification Reuse, easy file uploads and those features we’re going to explore in the following article.

With a few lines of code and Jersey I have written a RESTful web service that allows us to explore the features of the REST-assured framework and to run tests against this service.

 

Prerequisites

We’re going to need a JDK and Maven .. nothing more …

The REST Service to be tested

I have added a demo web application that exposes a RESTful service (Jersey used here) and allows us to run our tests against it. There are two possible ways to run the web app:

  • Check out the tutorial sources (see chapter “Tutorial Sources Download“) and run
    mvn tomcat:run
  • Or simply download the following war file from my Bitbucket repository and deploy it to a valid web container like Tomcat, Jetty etc..
  • If you’re running the app and open the URL http://localhost:8080 in your browser you should be able to see a nice overview of the exported service methods
    REST Service Overview

    REST Service Overview

Adding REST-assured to your Maven project

You only need to add the following dependencies to your pom.xml to use REST-assured  and – of course JUnit..

<dependency>
 <groupId>junit</groupId>
 <artifactId>junit</artifactId>
 <version>4.10</version>
 <scope>test</scope>
</dependency>
<dependency>
 <groupId>com.jayway.restassured</groupId>
 <artifactId>rest-assured</artifactId>
 <version>1.4</version>
 <scope>test</scope>
</dependency>

Examples

I have added some examples for different scenarios to test .. headers, status codes, cookies, file uploads etc ..

Verify JSON GET Request

We’re testing a simple response containing some JSON data here ..

  • Request URL: /service/single-user
  • Request Method: GET
  • Response Content-Type: application/json
  • Response Body:
    {
      "email":"test@hascode.com",
      "firstName":"Tim",
      "id":"1",
      "lastName":"Testerman"
    }

And this is our test case:

@Test
public void testGetSingleUser() {
  expect().
    statusCode(200).
    body(
      "email", equalTo("test@hascode.com"),
      "firstName", equalTo("Tim"),
      "lastName", equalTo("Testerman"),
      "id", equalTo("1")).
    when().
    get("/service/single-user");
}

Using JsonPath

This time we’re using JsonPath to programatically test the returned JSON structure..

  • Request URL: /service/single-user
  • Request Method: GET
  • Response Content-Type: application/json
  • Response Body
    {
      "email":"test@hascode.com",
      "firstName":"Tim",
      "id":"1",
      "lastName":"Testerman"
    }

And this is our test:

@Test
public void testGetSingleUserProgrammatic() {
  Response res = get("/service/single-user");
  assertEquals(200, res.getStatusCode());
  String json = res.asString();
  JsonPath jp = new JsonPath(json);
  assertEquals("test@hascode.com", jp.get("email"));
  assertEquals("Tim", jp.get("firstName"));
  assertEquals("Testerman", jp.get("lastName"));
  assertEquals("1", jp.get("id"));
}

Using Groovy Closures

JsonPath allows us to use Groovy closures to perform searches on the returned JSON structure.

  • Request URL: /service/persons/json
  • Request Method: GET
  • Response Content-Type: application/json
  • Response Body
    {
    	"person":[
    	{
    		"@id":"1",
    		"email":"test@hascode.com",
    		"firstName":"Tim",
    		"lastName":"Testerman"
    	},{
    		"@id":"20",
    		"email":"dev@hascode.com",
    		"firstName":"Sara",
    		"lastName":"Stevens"
    	},{
    		"@id":"11",
    		"email":"devnull@hascode.com",
    		"firstName":"Mark",
    		"lastName":"Mustache"
    	}
    	]
    }

And this is our test – we’re searching for a person whose email matches the pattern /test@/:

@Test
public void testFindUsingGroovyClosure() {
  String json = get("/service/persons/json").asString();
  JsonPath jp = new JsonPath(json);
  jp.setRoot("person");
  Map person = jp.get("find {e -> e.email =~ /test@/}");
  assertEquals("test@hascode.com", person.get("email"));
  assertEquals("Tim", person.get("firstName"));
  assertEquals("Testerman", person.get("lastName"));
}

Verifying XML

Now we’re going to validate returned XML

  • Request URL: /service/single-user/xml
  • Request Method: GET
  • Response Content-Type: application/xml
  • Response Body
    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <user>
      <email>test@hascode.com</email>
      <firstName>Tim</firstName>
      <id>1</id>
      <lastName>Testerman</lastName>
    </user>

And this is our test:

@Test
public void testGetSingleUserAsXml() {
  expect().
    statusCode(200).
    body(
      "user.email", equalTo("test@hascode.com"),
      "user.firstName", equalTo("Tim"),
      "user.lastName", equalTo("Testerman"),
      "user.id", equalTo("1")).
    when().
    get("/service/single-user/xml");
}

XML using XPath

To validate complex XML structure XPath is way more comfortable here..

  • Request URL: /service/persons/xml
  • Request Method: GET
  • Response Content-Type: application/xml
  • Response Body
    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <people>
      <person id="1">
        <email>test@hascode.com</email>
        <firstName>Tim</firstName>
        <lastName>Testerman</lastName>
      </person>
      <person id="20">
        <email>dev@hascode.com</email>
        <firstName>Sara</firstName>
        <lastName>Stevens</lastName>
      </person>
      <person id="11">
        <email>devnull@hascode.com</email>
        <firstName>Mark</firstName>
        <lastName>Mustache</lastName>
      </person>
    </people>

And this is our test:

@Test
public void testGetPersons() {
 expect()
 .statusCode(200)
 .body(hasXPath("//*[self::person and self::person[@id='1'] and self::person/email[text()='test@hascode.com'] and self::person/firstName[text()='Tim'] and self::person/lastName[text()='Testerman']]"))
 .body(hasXPath("//*[self::person and self::person[@id='20'] and self::person/email[text()='dev@hascode.com'] and self::person/firstName[text()='Sara'] and self::person/lastName[text()='Stevens']]"))
 .body(hasXPath("//*[self::person and self::person[@id='11'] and self::person/email[text()='devnull@hascode.com'] and self::person/firstName[text()='Mark'] and self::person/lastName[text()='Mustache']]"))
 .when().get("/service/persons/xml");
}

XML verification vs a Schema

Now we’re going to validate the xml returned against a XML schema file

  • Request URL: /service/single-user/xml
  • Request Method: GET
  • Response Content-Type: application/xml
  • Response Body
    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <user>
      <email>test@hascode.com</email>
      <firstName>Tim</firstName>
      <id>1</id>
      <lastName>Testerman</lastName>
    </user>

This is the schema we’re using to validate in a file named user.xsd

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema">
 
	<element name="user">
		<complexType>
			<sequence>
				<element name="email">
					<simpleType>
						<restriction base="string">
							<pattern value=".+@.+"></pattern>
						</restriction>
					</simpleType>
				</element>
				<element name="firstName" type="string"></element>
				<element name="id" type="int"></element>
				<element name="lastName" type="string"></element>
			</sequence>
		</complexType>
	</element>
</schema>

And this is our test case:

@Test
public void testGetSingleUserAgainstSchema() {
  InputStream xsd = getClass().getResourceAsStream("/user.xsd");
  assertNotNull(xsd);
  expect().
  statusCode(200).
  body(
    matchesXsd(xsd)).
  when().
  get("/service/single-user/xml");
}

Handling Request Parameters

This is a simple example how to add some request parameters

  • Request URL: /service/user/create
  • Request Method: GET
  • Response Content-Type: application/json
  • Response Body
    {
      "email":"test@hascode.com",
      "firstName":"Tim",
      "id":"1",
      "lastName":"Testerman"
    }

And this is our test:

@Test
public void testCreateuser() {
  final String email = "test@hascode.com";
  final String firstName = "Tim";
  final String lastName = "Tester";
 
  given().
    parameters(
      "email", email,
      "firstName", firstName,
      "lastName", lastName).
  expect().
    body("email", equalTo(email)).
    body("firstName", equalTo(firstName)).
    body("lastName", equalTo(lastName)).
  when().
  get("/service/user/create");
}

HTTP Status Code

Now an example how to verify HTTP headers – in the following example, a 404 Page Not Found is returned ..

  • Request URL: /service/status/notfound
  • Request Method: GET
  • Response Content-Type: text/plain
  • Response Status: 404 / Page Not Found

And this is our test:

@Test
public void testStatusNotFound() {
  expect().
    statusCode(404).
  when().
  get("/service/status/notfound");
}

Authentication

In this example we’re handling basic authentication ..

Basic Authentication secured REST Service

Basic Authentication secured REST Service

  • Request URL: /service/secure/person
  • Request Method: GET
  • Response Content-Type: text/plain
  • Response Status: 401 Unauthorized/ 200 Status Ok (when logged in with username=admin and password=admin)

And this is our test:

@Test
public void testAuthenticationWorking() {
  // we're not authenticated, service returns "401 Unauthorized"
  expect().
    statusCode(401).
  when().
  get("/service/secure/person");
 
  // with authentication it is working
  expect().
    statusCode(200).
  when().
    with().
      authentication().basic("admin", "admin").
  get("/service/secure/person");
}

Setting HTTP Headers

In the following example we’re setting some HTTP headers. The value of the HTTP header named “myparam” is returned by the REST service in the response body..

  • Request URL: /service/single-user
  • Request Method: GET
  • Response Content-Type: text/plain
  • Response Body: #value-of-myparam#

And this is our test:

@Test
public void testSetRequestHeaders() {
  expect().
    body(equalTo("TEST")).
  when().
    with().
    header("myparam", "TEST").
  get("/service/header/print");
 
  expect().
    body(equalTo("foo")).
  when().
    with().
    header("myparam", "foo").
  get("/service/header/print");
}

Verifying HTTP Headers

Now we’re going to verify HTTP response headers

  • Request URL: /service/header/multiple
  • Request Method: GET
  • Response Content-Type: text/plain
  • Response Header: customHeader1:foo, anotherHeader:bar

And this is our test:

@Test
public void testReturnedHeaders() {
  expect().
    headers("customHeader1", "foo", "anotherHeader", "bar").
  when().
  get("/service/header/multiple");
}

Setting Cookies

The following example shows how to set cookies. The REST service sends a 403 / Forbidden until a cookie with name=authtoken and value=abcdef is send.

  • Request URL: /service/access/cookie-token-secured
  • Request Method: GET
  • Response Content-Type: application/json
  • Response Status: 403 / 200

And this is our test:

@Test
public void testAccessSecuredByCookie() {
  expect().
    statusCode(403).
  when().
  get("/service/access/cookie-token-secured");
 
  given().
    cookie("authtoken", "abcdef").
  expect().
    statusCode(200).
  when().
  get("/service/access/cookie-token-secured");
}

Verifying Cookies

This is how to verify cookies set by the service. The service returns the request parameter “name” as the value of the cookie named “userName”:

  • Request URL: /service/cookie/modify
  • Request Method: GET
  • Request Parameter: name
  • Response Cookie: userName:#value-of-name#

And this is our test:

@Test
public void testModifyCookie() {
  expect().
    cookie("userName", equalTo("Ted")).
  when().
    with().param("name", "Ted").
  get("/service/cookie/modify");
 
  expect().
    cookie("userName", equalTo("Bill")).
  when().
    with().param("name", "Bill").
  get("/service/cookie/modify");
}

File Uploads

The following example shows how to handle file uploads. We’re sending a text file to the REST service and the service returns the file content as a string in the response body.

  • Request URL: /service/file/upload
  • Request Method: GET
  • Request Content-Type: multipart/form-data
  • Response Content-Type: text/plain
  • Response Body: #file-content#

And this is our test:

@Test
public void testFileUpload() {
  final File file = new File(getClass().getClassLoader()
      .getResource("test.txt").getFile());
  assertNotNull(file);
  assertTrue(file.canRead());
  given().
    multiPart(file).
  expect().
    body(equalTo("This is an uploaded test file.")).
  when().
  post("/service/file/upload");
}

Registering custom parsers for MIME-types

Sometimes you’ve got to handle a RESTful service that returns an invalid content type so that REST-assured does not know which parser to use to process the response. This is not a real problem though because the framework allows you to register parsers for a given content type as shown in the example below:

  • Request URL: /service/detail/json
  • Request Method: GET
  • Response Content-Type: text/json
  • Response Body:
    {"test":true}

And this is our test:

@Test
public void testRegisterParserForUnknownContentType() {
  RestAssured.registerParser("text/json", Parser.JSON);
  expect().
    body("test", equalTo(true)).
  when().
  get("/service/detail/json");
}

Specification reuse

Another nice feature of the REST-assured framework the possibility to create specifications and reuse, modify or extend them in several tests.

  • Request URL: /service/single-user / /service/user/create
  • Request Method: GET
  • Response Content-Type: application/json
  • Response Body
    {
      "email":"test@hascode.com",
      "firstName":"Tim",
      "id":"1",
      "lastName":"Testerman"
    }

And this is our test:

@Test
public void testSpecReuse() {
  ResponseSpecBuilder builder = new ResponseSpecBuilder();
  builder.expectStatusCode(200);
  builder.expectBody("email", equalTo("test@hascode.com"));
  builder.expectBody("firstName", equalTo("Tim"));
  builder.expectBody("lastName", equalTo("Testerman"));
  builder.expectBody("id", equalTo("1"));
  ResponseSpecification responseSpec = builder.build();
 
  // now we're able to use this specification for this test
  expect().
    spec(responseSpec).
  when().
  get("/service/single-user");
 
  // now re-use for another test that returns similar data .. you may
  // extend the specification with further tests as you wish
  final String email = "test@hascode.com";
  final String firstName = "Tim";
  final String lastName = "Testerman";
 
  expect().
    spec(responseSpec).
  when().
    with().
    parameters(
      "email", email,
      "firstName", firstName,
      "lastName",lastName).
  get("/service/user/create");
}

Troubleshooting

  • WARNING: Cannot find parser for content-type: text/json — using default parser.” – The framework does not know for sure which parser to use. Register the corresponding parser like this: e.g. RestAssured.registerParser(“text/json”, Parser.JSON);
  • “If I use the War file, the path is no longer localhost:8080, but becomes http://localhost:8080/rest-assured-example/.” -  specify the changed context path in the get() method or – more comfortable – define it as a global setting e.g. like this one
    @Before
     public void setUp(){
     RestAssured.basePath = "yourbasepath";
     }

Tutorial Sources

I have put the source from this tutorial on my Bitbucket repository – download it there or check it out using Mercurial:

hg clone https://bitbucket.org/hascode/rest-assured-samples

Slideshow

Resources

Tags: , , , , , , , ,

38 Responses to “Testing RESTful Web Services made easy using the REST-assured Framework”

  1. Fergus MacDermot Says:

    That’s really nice. How do you get the exported view? Is that a default Jersey feature? I know the wadl is produced, but didn’t know this part. Thanks for your examples too. Very helpful. We are trying to work out whether to use something like this, jbehave, or custom….

  2. suranjana Says:

    THANKS!!!!

  3. mark Says:

    Where can I find the demo application war file?

  4. micha kops Says:

    Hi, you can download the war file from my Bitbucket repository.

  5. mark Says:

    Thanks for the .war. I didn’t see it when I was looking at your Bitbucket repository. Now that I’ve got the .war deployed and tomcat running, I tried your example for testGetSingleUser(). I had to change get(“/service/single-user”); to get(“/rest-assured-example/service/single-user”); in order for it to find the resource and return a status code of 200.

  6. mark Says:

    Running the XML using XPath example, I’m getting an error:

    java.lang.AssertionError: Body doesn’t match.
    Expected:
    an XML document with XPath //person[@id='1']/email[.='test@hascode.com'] and firstName=’Tim’ and lastName=’Testerman’
    Actual:
    test@hascode.comTimTestermandev@hascode.comSaraStevensdevnull@hascode.comMarkMustache

    I’m using this code
    expect().statusCode(200)
    .body(hasXPath(“//person[@id='1']/email[.='test@hascode.com'] and firstName=’Tim’ and lastName=’Testerman’”))
    .body(hasXPath(“//person[@id='20']/email[.='dev@hascode.com'] and firstName=’Sara’ and lastName=’Stevens’”))
    .body(hasXPath(“//person[@id='11']/email[.='devnull@hascode.com'] and firstName=’Mark’ and lastName=’Mustache’”))
    .when().get(“/rest-assured-example/service/persons/xml”);

    Thanks for any help you can provide so I can understand how this works.

  7. micha kops Says:

    Works for me .. using mvn tomcat:run as well as using a deployed war archive on a tomcat instance. but I’ve noticed that the xpath expression was not well defined and precise enough .. I’ve fixed this and updated the example .. thanks for mentioning!

  8. mark Says:

    Thanks Micha. The new code works.

  9. Lu Says:

    Hello, Micha. Excellent tutorial. If I use the War file, the path is no longer localhost:8080, but becomes http://localhost:8080/rest-assured-example/. This causes the tests to fail. How do I fix this? I am currently looking at your source code to find it.
    Thanks so much !!

  10. micha kops Says:

    Thanks! You just simply need to specify the new context path – one way is to specify it in the get() method but it is way more comfortable to specify it globally using RestAssured.basePath = “yourbasepath”;

  11. Lu Says:

    Hi again, Micha. I should have found that answer right above. :( Anyway, any ideas why I am
    unable to do your public void testFileUpload() on JUnit? Everything else works.

  12. micha kops Says:

    No problem :) Are you getting any error here? Does the file exist in your classpath? Have you modified the original example somehow? Does the servlet container return any error or is there an error displayed in your server’s logs?

  13. Lu Says:

    final File file = new File( getClass().getClassLoader()
    .getResource( “test.txt” ).getFile() );

    java.lang.NullPointerException
    at it.RestAssuredSampleServiceIT.testFileUpload(RestAssuredSampleServiceIT.java:154)

    I see the file in the project as you listed it, and have not changed anything.

  14. micha kops Says:

    Hmm.. could you please run the test using some external file and an absolute path? Have you included the dependency for jersey-multipart (com.sun.jersey.contribs:jersey-multipart) in your project?

  15. Lu Says:

    Micha, I don’t know why but I searched and the solution was to move the test.txt to the \target\classes folder.

  16. micha kops Says:

    Ok – I’m glad it finally worked somehow :)

  17. Chantme Says:

    Hi Micha

    I took the last war file and deployed it on Tomcat 7, I get a 404 error for every REST call from your welcome test page.

    Tomcat is “Apache Tomcat 7.0.30 Server”, installed as a service on Windows. Java is “C:\Program Files\Java\jre7\bin\client\jvm.dll”

    I took the same war file, and installed it on another machine with Tomcat “Apache Tomcat 6.0.36 “, Java “C:\Program Files\Java\jre7\bin\client\jvm.dll”, everything works fine.

    Does anybody had the same problem ?

  18. micha kops Says:

    Hi,

    what context path did you use for the application? I bet it differs from the one used in my tutorial :)

    Best regards

    Micha

  19. Lisa Says:

    Hi, Micha,

    Thanks for putting together such a nice tutorial! It is really helpful for me to understand rest-assured better. I am trying to figure out what framework to use for my rest web service testing and have some further questions on rest-assured for you.

    Do you happen to have an example to use rest-assured for https web service?

    Also for a web service that supports both xml and json, is there any way to write same test to handle both these two response format? If not, the tests will double :( .

    Also for a test case, say, 1. user A (may be an admin user) logs in, 2. A create a user B, 3. A then retrieves user B’s info to verify that user B is created correctly.
    step 2 and 3 will need to send out the cookies returned from step 1. Will tester have to set cookie in each request? i was hopping that rest-assured will support updating some default cookies based on server response, then the next http request will by default send the updated cookies. Do you happen to know if this is supported by rest-assured?

    Thanks in advance for your help.
    Lisa

  20. Shama Says:

    Hi,

    I am getting error marked in red for “equalTo” when is use
    body(
    “email”, equalTo(“test@hascode.com”),
    “firstName”, equalTo(“Tim”),
    “lastName”, equalTo(“Testerman”),
    “id”, equalTo(“1″))

    Please guide me. Where am i going wrong

    Thanks,
    Shama

  21. micha kops Says:

    Hi, does the test fail because other values are returned? or are you getting an error in your IDE, perhaps have forgotten the static import for equalTo e.g. import static org.hamcrest.Matchers.equalTo;

    Have you assured that your REST-service is responsive? By adding .log().all() to the response and request specification you’ll receive detailed information what the client sends to the server and the server’s response.

  22. Eduardo Silva Says:

    Hi Micha,

    Again, thank you for this very nice tutorial (today is the third document I read from you about REST-Assured and Jersey Testing Framework… I am evaluating which one to use, and inclining to go with REST-Assured)… this very nice coverage of several capabilities of REST-Assure, with code to test as we read!!

    I also had “failing” tests due to the URL/path of the deployed web service (in Tomcat from Eclipse), by adding the following “@Before” it solved the problem (you have also suggested this in another comment above):

    @Before
    public void setUp(){
    RestAssured.basePath = “http://localhost:8080/rest-assured-example”;
    }

    Cheers!

  23. micha kops Says:

    Hi Eduardo,

    thanks for your kind feedback!

    Cheers

    Micha

  24. Vamsi Says:

    Hi Micha,

    Excellent tutorial.

    Do you happen to have an example to use rest-assured for https web service?

    Thanks
    Vamsi

  25. micha kops Says:

    Thanks for the kind feedback!

    In most cases, HTTPS should work out of the box but there are some cases where you might run into trouble:

    1) The server uses an invalid certificate (you’re getting an SSLPeerUnverifiedException)
    given().relaxedHTTPSValidation().when().get("https://yourserver.com");
    or using specifications: RestAssured.useRelaxedHTTPSValidation();

    You may even specify a Java keystore file if you need to:
    given().keystore("/pathToJksInClassPath", )..
    or using specifications: RestAssured.keystore("/pathToJksInClassPath", );

    If you’ve already loaded a keystore, you may use this keystore, too:
    RestAssured.trustStore(keystore);

    2) The server certificate references an invalid hostname
    In this case, you don’t need to import a keystore .. simply use:
    RestAssured.config = RestAssured.config().sslConfig(sslConfig().allowAllHostnames());

    or in a concrete request
    given().config(RestAssured.config().sslConfig(sslConfig().allowAllHostnames()). .. ;

    Further information can be found in the rest-assured documentation.

  26. Vamsi Says:

    Hi Micha,

    Thank you detailed explanation. I am not able to resolve my issue by using relaxed https validation.

    RestAssured.baseURI = “https://stage3.test.com”;

    RestAssured.port = 443;
    RestAssured.urlEncodingEnabled = false;

    String body = given()
    .relaxedHTTPSValidation()
    .header(“Accept”, “application/json”)
    .header(“IMAuthId”, “10000155408″)
    .header(“IMTicketId”, “e95c9ebcc435e7aa9d8d46ffd5d1345408764a98aa7e3d6b43d30d0cfa68d937e13392c99105b1e92c1b2a6abb5ee6ca3a0c61f4d2e440c0a925724aeb8ab3fb2772cbb49d27d6a1e36219dfdb122005c9fef0b1564c183a2f8f532ad39668065dd12e1b3056e3a613beba523e97a5f45f698d45b9620ef93906926883b2742cac9d2c9ff5a40ec48f81f40390aa3d3a08c53cec2de0d250368eaf8c962b90764011c982334f73ed332d950378cccd88f8076ee937aa75674a36e1b9f761cc36″)
    .header(“IMIV”, “54112aeb8006cce4b800033c1d4efed5″)

    .expect()
    .log().all()
    .statusCode(200)

    .when()
    .get(“/services/api/v1/product/”)
    .prettyPrint();

    Output:
    here is the http response what i am getting.

    HTTP/1.1 404 Not Found
    Cache-Control: no-cache
    Pragma: no-cache
    Content-Type: application/json; charset=utf-8
    Expires: -1
    Server: Microsoft-IIS/7.5
    Access-Control-Allow-Origin: *
    Access-Control-Request-Method: *
    Access-Control-Request-Headers: *
    Access-Control-Allow-Headers: accept, imauthid, origin, imiv, imticketid, Content-Type
    Access-Control-Allow-Methods: *
    Date: Fri, 07 Feb 2014 08:18:20 GMT
    Content-Length: 232

    {
    “$id”: “1″,
    “Message”: “No HTTP resource was found that matches the request URI ‘http://stage3.test.com:81/services/api/v1/product/’.”,
    “MessageDetail”: “No type was found that matches the controller named ‘product’.”
    }
    FAILED: test
    java.lang.AssertionError: 1 expectation failed.
    Expected status code doesn’t match actual status code .

    Kindly help me how to resolve this issue.

    Thanks in advance.

    Thanks
    Vamsi

  27. micha kops Says:

    Are you sure that your base URI and port specification is applied? In your response I’m reading “http://stage3…” and port 81?

  28. Vamsi Says:

    Hi Micha,

    Thanks for quick response, i am new to Rest Assured and all our services can access only https.

    I am really not sure how to check port specification applied, but yes…wat ever i change i am getting test is happening only on port81.

    Kindly help me to debug and fix the issue.

    Thanks
    Vamsi

  29. micha kops Says:

    Do you override this setting somewhere? rest assured’s default port is 8080, host=localhost ..
    When running in a JUnit test you could use the setup method to set your requirements here ..

    @Before
    public void setup(){
    // .. your setup
    }

  30. Vamsi Says:

    Hi Micha,

    I am not overriding any settings as i am not aware of these procedure:(. Can you please help me in more detail and i am using testng runner.

    Thanks
    Vamsi

  31. Vamsi Says:

    Hi Micha,

    i just did a small correction in my script

    given()
    .port(1234)

    it returns following error: Connection to https://stage3.test.com:1234 refused.

    Thanks
    Vamsi

  32. micha kops Says:

    Good to hear, that adjusting your test to your specified port and connection type is working for you now!

  33. Vamsi Says:

    sorry, its not correct port.. i just tried with some dummy port which resulted into connection refuse. I need still your help on port overriding to 443. Kindly help me on this.

    i am new to Rest assured and this is my first trial… please let me know how to resolve this issue.

    Thanks
    Vamsi

  34. Vamsi Says:

    Hi Micha,

    sorry for keepon posting.

    little more progress.

    javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

    Thanks
    Vamsi

  35. micha kops Says:

    Maybe you need to add your own trust store

  36. vamsi Says:

    Hi Micha,

    I have added trust store, here is the next error i am getting.

    Script:

    import com.jayway.restassured.*;
    import com.jayway.restassured.path.xml.XmlPath;
    import com.jayway.restassured.response.Response;
    import com.jayway.restassured.matcher.RestAssuredMatchers.*;

    import static com.jayway.restassured.RestAssured.*;
    import static com.jayway.restassured.matcher.RestAssuredMatchers.*;
    import com.jayway.restassured.response.Response;
    import static org.hamcrest.Matchers.*;
    import org.hamcrest.Matchers.*;
    import org.testng.Assert;
    import org.testng.annotations.Test;

    import java.util.List;

    import static com.jayway.restassured.RestAssured.given;
    import static org.hamcrest.CoreMatchers.hasItem;

    public class Test_RestAssured {
    @Test
    public static void test(){
    //RestAssured.port = 443;
    RestAssured.baseURI = “https://stage3.test.com”;
    String body = given()
    .port(443)
    .keystore(“c:/users/autolab/truststore_javanet.jks”, “abcdef”)
    .relaxedHTTPSValidation()
    .header(“Accept”, “application/json”, “ImAuthId”, “10000155408″)
    .header(“IMTicketId”, “e95c9ebcc435e7aa9d8d46ffd5d1345408764a98aa7e3d6b43d30d0cfa68d937e13392c99105b1e92c1b2a6abb5ee6ca3a0c61f4d2e440c0a925724aeb8ab3fb2772cbb49d27d6a1e36219dfdb122005c9fef0b1564c183a2f8f532ad39668065dd12e1b3056e3a613beba523e97a5f45f698d45b9620ef93906926883b2742cac9d2c9ff5a40ec48f81f40390aa3d3a08c53cec2de0d250368eaf8c962b90764011c982334f73ed332d950378cccd88f8076ee937aa75674a36e1b9f761cc36″)
    .header(“IMIV”, “54112aeb8006cce4b800033c1d4efed5″)

    .expect()
    .log().all()
    .statusCode(200)

    .when()
    .get(“/services/api/v1/product”)
    .prettyPrint();

    }

    }

    Here is the Https Response and error:

    [TestNG] Running:
    C:\Users\autolab\AppData\Local\Temp\testng-eclipse-660754300\testng-customsuite.xml

    HTTP/1.1 404 Not Found
    Cache-Control: no-cache
    Pragma: no-cache
    Content-Type: application/json; charset=utf-8
    Expires: -1
    Server: Microsoft-IIS/7.5
    Access-Control-Allow-Origin: *
    Access-Control-Request-Method: *
    Access-Control-Request-Headers: *
    Access-Control-Allow-Headers: accept, imauthid, origin, imiv, imticketid, Content-Type
    Access-Control-Allow-Methods: *
    Date: Sat, 08 Feb 2014 10:05:19 GMT
    Content-Length: 228

    {
    “$id”: “1″,
    “Message”: “No HTTP resource was found that matches the request URI ‘https:/stage3.test.com/services/api/v1/product’.”,
    “MessageDetail”: “No type was found that matches the controller named ‘product’.”
    }
    FAILED: test
    java.lang.AssertionError: 1 expectation failed.
    Expected status code doesn’t match actual status code .

    Please help me to proceed further.

    Thanks in advance.

    Thanks
    Vamsi

  37. vamsi Says:

    Hi Micha,

    I’ve added trust store, still i am getting below issue. Please help to proceed further.

    Script:
    public class Test_RestAssured {
    @Test
    public static void test(){
    RestAssured.urlEncodingEnabled = false;

    String body = given()
    .port(443)
    .keystore(“c:/users/autolab/truststore_javanet.jks”, “abcdef”)
    .relaxedHTTPSValidation()
    .header(“Accept”, “application/json”, “ImAuthId”, “10000155408″)
    .header(“IMTicketId”, “e95c9ebcc435e7aa9d8d46ffd5d1345408764a98aa7e3d6b43d30d0cfa68d937e13392c99105b1e92c1b2a6abb5ee6ca3a0c61f4d2e440c0a925724aeb8ab3fb2772cbb49d27d6a1e36219dfdb122005c9fef0b1564c183a2f8f532ad39668065dd12e1b3056e3a613beba523e97a5f45f698d45b9620ef93906926883b2742cac9d2c9ff5a40ec48f81f40390aa3d3a08c53cec2de0d250368eaf8c962b90764011c982334f73ed332d950378cccd88f8076ee937aa75674a36e1b9f761cc36″)
    .header(“IMIV”, “54112aeb8006cce4b800033c1d4efed5″)

    .expect()
    .log().all()
    .statusCode(200)

    .when()
    .get(“/services/api/v1/product”)
    .prettyPrint();
    }

    }

    output:

    [TestNG] Running:
    C:\Users\autolab\AppData\Local\Temp\testng-eclipse-660754300\testng-customsuite.xml

    HTTP/1.1 404 Not Found
    Cache-Control: no-cache
    Pragma: no-cache
    Content-Type: application/json; charset=utf-8
    Expires: -1
    Server: Microsoft-IIS/7.5
    Access-Control-Allow-Origin: *
    Access-Control-Request-Method: *
    Access-Control-Request-Headers: *
    Access-Control-Allow-Headers: accept, imauthid, origin, imiv, imticketid, Content-Type
    Access-Control-Allow-Methods: *
    Date: Sat, 08 Feb 2014 10:05:19 GMT
    Content-Length: 228

    {
    “$id”: “1″,
    “Message”: “No HTTP resource was found that matches the request URI ‘https://stage3.test.com/services/api/v1/product’.”,
    “MessageDetail”: “No type was found that matches the controller named ‘product’.”
    }
    FAILED: test
    java.lang.AssertionError: 1 expectation failed.
    Expected status code doesn’t match actual status code .

    Thanks
    Vamsi

  38. micha kops Says:

    Seems like you’ve managed to handle the HTTPS problems. Is https://stage3.test.com/services/api/v1/product with method=GET and content-type header application/json correct? Are you able to access the webservice using curl or since it’s using GET .. your browser when using the designated target?

Leave a Reply

Please leave these two fields as-is:

Protected by Invisible Defender. Showed 403 to 80,933 bad guys.

Search
Categories