|
||||||||||
PREV CLASS NEXT CLASS | FRAMES NO FRAMES | |||||||||
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |
java.lang.Objectcom.jayway.restassured.RestAssured
public class RestAssured
REST Assured is a Java DSL for simplifying testing of REST based services built on top of HTTP Builder. It supports POST, GET, PUT, DELETE and HEAD requests and to verify the response of these requests. Usage examples:
{ "lotto":{ "lottoId":5, "winning-numbers":[2,45,34,23,7,5,3], "winners":[{ "winnerId":23, "numbers":[2,45,34,23,3,5] },{ "winnerId":54, "numbers":[52,3,12,11,18,22] }] } }REST assured can then help you to easily make the GET request and verify the response. E.g. if you want to verify that lottoId is equal to 5 you can do like this:
expect().body("lotto.lottoId", equalTo(5)).when().get("/lotto");or perhaps you want to check that the winnerId's are 23 and 54:
expect().body("lotto.winners.winnerId", hasItems(23, 54)).when().get("/lotto");
<greeting> <firstName>{params("firstName")}</firstName> <lastName>{params("lastName")}</lastName> </greeting>i.e. it sends back a greeting based on the firstName and lastName parameter sent in the request. You can easily perform and verify e.g. the firstName with REST assured:
with().parameters("firstName", "John", "lastName", "Doe").expect().body("greeting.firstName", equalTo("John")).when().post("/greetXML");If you want to verify both firstName and lastName you may do like this:
with().parameters("firstName", "John", "lastName", "Doe").expect().body("greeting.firstName", equalTo("John")).and().body("greeting.lastName", equalTo("Doe")).when().post("/greetXML");or a little shorter:
with().parameters("firstName", "John", "lastName", "Doe").expect().body("greeting.firstName", equalTo("John"), "greeting.lastName", equalTo("Doe")).when().post("/greetXML");
expect().body(hasXPath("/greeting/firstName", containsString("Jo"))).given().parameters("firstName", "John", "lastName", "Doe").when().post("/greetXML");or
expect().body(hasXPath("/greeting/firstName[text()='John']")).with().parameters("firstName", "John", "lastName", "Doe").post("/greetXML");
expect().body(matchesXsd(xsd)).when().get("/carRecords");DTD example:
expect().body(matchesDtd(dtd)).when().get("/videos");
matchesXsd
and matchesDtd
are Hamcrest matchers which you can import from RestAssuredMatchers
.
given().cookie("username", "John").then().expect().body(equalTo("username")).when().get("/cookie");
given().header("MyHeader", "Something").and(). .. given().headers("MyHeader", "Something", "MyOtherHeader", "SomethingElse").and(). ..
given().contentType(ContentType.TEXT). ..
given().request().body("some body"). .. // Works for POST and PUT requests given().request().body(new byte[]{42}). .. // Works for POST
expect().cookie("cookieName", "cookieValue"). .. expect().cookies("cookieName1", "cookieValue1", "cookieName2", "cookieValue2"). .. expect().cookies("cookieName1", "cookieValue1", "cookieName2", containsString("Value2")). ..
expect().statusCode(200). .. expect().statusLine("something"). .. expect().statusLine(containsString("some")). ..
expect().header("headerName", "headerValue"). .. expect().headers("headerName1", "headerValue1", "headerName2", "headerValue2"). .. expect().headers("headerName1", "headerValue1", "headerName2", containsString("Value2")). ..
expect().contentType(ContentType.JSON). ..
Greeting greeting = get("/greeting").as(Greeting.class);
Greeting greeting = new Greeting(); greeting.setFirstName("John"); greeting.setLastName("Doe"); given().body(greeting).when().post("/greeting");See the javadoc for the body method for more details.
expect().body(equalsTo("something")). .. expect().content(equalsTo("something")). .. // Same as above
given().auth().basic("username", "password").expect().statusCode(200).when().get("/secured/hello");Other supported schemes are OAuth and certificate authentication.
given().port(80). ..or simply:
.. when().get("http://myhost.org:80/doSomething");
..when().get("/name?firstName=John&lastName=Doe");
XmlPath
or JsonPath
to
easily parse XML or JSON data from a response.
String xml = post("/greetXML?firstName=John&lastName=Doe").andReturn().asString(); // Now use XmlPath to get the first and last name String firstName = with(xml).get("greeting.firstName"); String lastName = with(xml).get("greeting.firstName"); // or a bit more efficiently: XmlPath xmlPath = new XmlPath(xml).setRoot("greeting"); String firstName = xmlPath.get("firstName"); String lastName = xmlPath.get("lastName");
String json = get("/lotto").asString(); // Now use JsonPath to get data out of the JSON body int lottoId = with(json).getInt("lotto.lottoId); ListwinnerIds = with(json).get("lotto.winners.winnerId"); // or a bit more efficiently: JsonPath jsonPath = new JsonPath(json).setRoot("lotto"); int lottoId = jsonPath.getInt("lottoId"); List winnderIds = jsonPath.get("winnders.winnderId");
RestAssured.registerParser(<content-type>, <parser>);E.g. to register that content-type
'application/vnd.uoml+xml'
should be parsed using the XML parser do:
RestAssured.registerParser("application/vnd.uoml+xml", Parser.XML);You can also unregister a parser using:
RestAssured.unregisterParser("application/vnd.uoml+xml");If can also specify a default parser for all content-types that do not match a pre-defined or registered parser. This is also useful if the response doesn't contain a content-type at all:
RestAssured.defaultParser = Parser.JSON;
ResponseSpecBuilder
and RequestSpecBuilder
like this:
RequestSpecification requestSpec = new RequestSpecBuilder().addParameter("parameter1", "value1").build(); ResponseSpecification responseSpec = new ResponseSpecBuilder().expectStatusCode(200).build(); given(). spec(requestSpec). expect(). spec(responseSpec). body("x.y.z", equalTo("something")). when(). get("/something");
given().filter(ResponseLoggingFilter.logResponseIfStatusCodeIs(302)). ..will log/print the response body to after each request.
RestAssured.baseURI = "http://myhost.org"; RestAssured.port = 80; RestAssured.basePath = "/resource"; RestAssured.authentication = basic("username", "password"); RestAssured.rootPath = "store.book";This means that a request like e.g.
get("/hello")
goes to: http://myhost.org:8080/resource/hello
which basic authentication credentials "username" and "password". See rootPath
for more info about setting the root paths, filters(java.util.List)
for setting
default filters and keystore(String, String)
for setting the default keystore when using SSL.RestAssured.reset();
In order to use REST assured effectively it's recommended to statically import methods from the following classes:
Field Summary | |
---|---|
static AuthenticationScheme |
authentication
Set an authentication scheme that should be used for each request. |
static String |
basePath
A base path that's added to the baseURI by REST assured when making requests. |
static String |
baseURI
The base URI that's used by REST assured when making requests if a non-fully qualified URI is used in the request. |
static RestAssuredConfig |
config
Define a configuration for redirection settings and http client parameters (default is null ). |
static AuthenticationScheme |
DEFAULT_AUTH
|
static String |
DEFAULT_BODY_ROOT_PATH
|
static String |
DEFAULT_PATH
|
static int |
DEFAULT_PORT
|
static String |
DEFAULT_SESSION_ID_VALUE
|
static String |
DEFAULT_URI
|
static boolean |
DEFAULT_URL_ENCODING_ENABLED
|
static Parser |
defaultParser
Specify a default parser. |
static int |
port
The port that's used by REST assured when it's left out of the specified URI when making a request. |
static RequestSpecification |
requestSpecification
Specify a default request specification that will be sent with each request. |
static ResponseSpecification |
responseSpecification
Specify a default response specification that will be sent with each request. |
static String |
rootPath
Set the default root path of the response body so that you don't need to write the entire path for each expectation. |
static String |
sessionId
Set the default session id value that'll be used for each request. |
static boolean |
urlEncodingEnabled
Specifies if Rest Assured should url encode the URL automatically. |
Constructor Summary | |
---|---|
RestAssured()
|
Method Summary | |
---|---|
static AuthenticationScheme |
basic(String userName,
String password)
Create a http basic authentication scheme. |
static AuthenticationScheme |
certificate(String certURL,
String password)
Sets a certificate to be used for SSL authentication. |
static Response |
delete(String path,
Map<String,?> pathParams)
Perform a DELETE request to a path . |
static Response |
delete(String path,
Object... pathParams)
Perform a DELETE request to a path . |
static AuthenticationScheme |
digest(String userName,
String password)
Use http digest authentication. |
static ResponseSpecification |
expect()
Start building the response part of the test com.jayway.restassured.specification. |
static List<Filter> |
filters()
|
static void |
filters(Filter filter,
Filter... additionalFilters)
The the default filters to apply to each request. |
static void |
filters(List<Filter> filters)
The the default filters to apply to each request. |
static AuthenticationScheme |
form(String userName,
String password)
Use form authentication. |
static AuthenticationScheme |
form(String userName,
String password,
FormAuthConfig config)
Use form authentication with the supplied configuration. |
static Response |
get(String path,
Map<String,?> pathParams)
Perform a GET request to a path . |
static Response |
get(String path,
Object... pathParams)
Perform a GET request to a path . |
static RequestSpecification |
given()
Start building the request part of the test com.jayway.restassured.specification. |
static RequestSender |
given(RequestSpecification requestSpecification,
ResponseSpecification responseSpecification)
When you have long specifications it can be better to split up the definition of response and request specifications in multiple lines. |
static Response |
head(String path,
Map<String,?> pathParams)
Perform a HEAD request to a path . |
static Response |
head(String path,
Object... pathParams)
Perform a HEAD request to a path . |
static KeystoreSpec |
keystore()
|
static KeystoreSpec |
keystore(File pathToJks,
String password)
Use a keystore located on the file-system. |
static KeystoreSpec |
keystore(String password)
Uses the user default keystore stored in @{user.home}/.keystore |
static KeystoreSpec |
keystore(String pathToJks,
String password)
The following documentation is taken from http://groovy.codehaus.org/modules/http-builder/doc/ssl.html: |
static AuthenticationScheme |
oauth(String consumerKey,
String consumerSecret,
String accessToken,
String secretToken)
Excerpt from the HttpBuilder docs: OAuth sign the request. |
static Response |
post(String path,
Map<String,?> pathParams)
Perform a POST request to a path . |
static Response |
post(String path,
Object... pathParams)
Perform a POST request to a path . |
static PreemptiveAuthProvider |
preemptive()
Return the http preemptive authentication specification for setting up preemptive authentication requests. |
static Response |
put(String path,
Object... pathParams)
Perform a PUT request to a path . |
static void |
registerParser(String contentType,
Parser parser)
Register a custom content-type to be parsed using a predefined parser. |
static Object |
requestContentType()
|
static void |
requestContentType(ContentType contentType)
Specify the default content type |
static void |
requestContentType(String contentType)
Specify the default content type |
static void |
reset()
Resets the baseURI , basePath , port , authentication and rootPath , requestContentType(com.jayway.restassured.http.ContentType) ,
responseContentType(com.jayway.restassured.http.ContentType) , filters(java.util.List) , requestSpecification , responseSpecification . |
static Object |
responseContentType()
|
static void |
responseContentType(ContentType contentType)
Specify the default content type (also sets the accept header). |
static void |
responseContentType(String contentType)
Specify the default content type (also sets the accept header). |
static void |
unregisterParser(String contentType)
Unregister the parser associated with the provided content-type |
static RequestSpecification |
with()
Start building the request part of the test com.jayway.restassured.specification. |
static List<Argument> |
withArgs(Object firstArgument,
Object... additionalArguments)
Slightly shorter version of withArguments(Object, Object...) . |
static List<Argument> |
withArguments(Object firstArgument,
Object... additionalArguments)
Create a list of arguments that can be used to create parts of the path in a body/content expression. |
Methods inherited from class java.lang.Object |
---|
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
Field Detail |
---|
public static final String DEFAULT_URI
public static final String DEFAULT_BODY_ROOT_PATH
public static final int DEFAULT_PORT
public static final String DEFAULT_PATH
public static final AuthenticationScheme DEFAULT_AUTH
public static final boolean DEFAULT_URL_ENCODING_ENABLED
public static final String DEFAULT_SESSION_ID_VALUE
public static String baseURI
public static int port
public static String basePath
baseURI
by REST assured when making requests. E.g. let's say that
the baseURI
is http://localhost
and basePath
is /resource
then
..when().get("/something");will make a request to
http://localhost/resource
.
Default basePath
value is empty.
public static boolean urlEncodingEnabled
RestAssured.baseURI = "https://jira.atlassian.com"; RestAssured.port = 443; RestAssured.urlEncodingEnabled = false; // Because "query" is already url encoded String query = "project%20=%20BAM%20AND%20issuetype%20=%20Bug"; String response = get("/rest/api/2.0.alpha1/search?jql={q}",query).andReturn().asString(); ...The
query
is already url encoded so you need to disable Rest Assureds url encoding to prevent double encoding.
public static AuthenticationScheme authentication
given().auth().none()..
public static RestAssuredConfig config
null
). E.g.
RestAssured.config = config().redirect(redirectConfig().followRedirects(true).and().maxRedirects(0));
config()
can be statically imported from RestAssuredConfig
.
public static String rootPath
expect(). body("x.y.firstName", is(..)). body("x.y.lastName", is(..)). body("x.y.age", is(..)). body("x.y.gender", is(..)). when(). get(..);you can use a root and do:
RestAssured.rootPath = "x.y"; expect(). body("firstName", is(..)). body("lastName", is(..)). body("age", is(..)). body("gender", is(..)). when(). get(..);
public static RequestSpecification requestSpecification
RestAssured.requestSpecification = new RequestSpecBuilder().addParameter("parameter1", "value1").build();means that for each request by Rest Assured "parameter1" will be equal to "value1".
public static Parser defaultParser
public static ResponseSpecification responseSpecification
RestAssured.responseSpecification = new ResponseSpecBuilder().expectStatusCode(200).build();means that for each response Rest Assured will assert that the status code is equal to 200.
public static String sessionId
SessionConfig
so it'll
override the session id value previously defined there (if any). If you need to change the sessionId cookie name you need to configure and supply the SessionConfig
to
RestAssured.config
.
Constructor Detail |
---|
public RestAssured()
Method Detail |
---|
public static KeystoreSpec keystore(String pathToJks, String password)
$ keytool -printcert -file EquifaxSecureGlobaleBusinessCA-1.crt Owner: CN=Equifax Secure Global eBusiness CA-1, O=Equifax Secure Inc., C=US Issuer: CN=Equifax Secure Global eBusiness CA-1, O=Equifax Secure Inc., C=US Serial number: 1 Valid from: Mon Jun 21 00:00:00 EDT 1999 until: Sun Jun 21 00:00:00 EDT 2020 Certificate fingerprints: MD5: 8F:5D:77:06:27:C4:98:3C:5B:93:78:E7:D7:7D:9B:CC SHA1: 7E:78:4A:10:1C:82:65:CC:2D:E1:F1:6D:47:B4:40:CA:D9:0A:19:45 Signature algorithm name: MD5withRSA Version: 3 ....Now, import that into a Java keystore file:
$ keytool -importcert -alias "equifax-ca" -file EquifaxSecureGlobaleBusinessCA-1.crt -keystore truststore.jks -storepass test1234 Owner: CN=Equifax Secure Global eBusiness CA-1, O=Equifax Secure Inc., C=US Issuer: CN=Equifax Secure Global eBusiness CA-1, O=Equifax Secure Inc., C=US Serial number: 1 Valid from: Mon Jun 21 00:00:00 EDT 1999 until: Sun Jun 21 00:00:00 EDT 2020 Certificate fingerprints: MD5: 8F:5D:77:06:27:C4:98:3C:5B:93:78:E7:D7:7D:9B:CC SHA1: 7E:78:4A:10:1C:82:65:CC:2D:E1:F1:6D:47:B4:40:CA:D9:0A:19:45 Signature algorithm name: MD5withRSA Version: 3 ... Trust this certificate? [no]: yes Certificate was added to keystoreNow you want to use this truststore in your client:
RestAssured.keystore("/truststore.jks", "test1234");or
given().keystore("/truststore.jks", "test1234"). ..
pathToJks
- The path to the JKS. REST Assured will first look in the classpath and if not found it will look for the JKS in the local file-systempassword
- The store passpublic static KeystoreSpec keystore(File pathToJks, String password)
keystore(String, String)
for more details.
pathToJks
- The path to JKS file on the file-systempassword
- The password for the keystore
keystore(String, String)
public static KeystoreSpec keystore(String password)
password
- - Use null for no password
public static void filters(List<Filter> filters)
filters
- The filter listpublic static void filters(Filter filter, Filter... additionalFilters)
filter
- The filter to setadditionalFilters
- An optional array of additional filters to setpublic static List<Filter> filters()
public static Object requestContentType()
public static Object responseContentType()
public static KeystoreSpec keystore()
public static void requestContentType(ContentType contentType)
contentType
- The content typepublic static void requestContentType(String contentType)
contentType
- The content typepublic static void responseContentType(ContentType contentType)
contentType
- The content typepublic static void responseContentType(String contentType)
contentType
- The content typepublic static ResponseSpecification expect()
expect().body("lotto.lottoId", equalTo(5)).when().get("/lotto");will expect that the response body for the GET request to "/lotto" should contain JSON or XML which has a lottoId equal to 5.
public static RequestSpecification with()
with().parameters("firstName", "John", "lastName", "Doe").expect().body("greeting.firstName", equalTo("John")).when().post("/greetXML");will send a POST request to "/greetXML" with request parameters firstName=John and lastName=Doe and expect that the response body containing JSON or XML firstName equal to John. The only difference between
with()
and given()
is syntactical.
public static List<Argument> withArguments(Object firstArgument, Object... additionalArguments)
String someSubPath = "else"; int index = 1; expect().body("something.%s[%d]", withArgs(someSubPath, index), equalTo("some value")). ..or if you have complex root paths and don't wish to duplicate the path for small variations:
expect(). root("filters.filterConfig[%d].filterConfigGroups.find { it.name == 'Gold' }.includes"). body("", withArgs(0), hasItem("first")). body("", withArgs(1), hasItem("second")). ..The key and arguments follows the standard formatting syntax of Java.
public static List<Argument> withArgs(Object firstArgument, Object... additionalArguments)
withArguments(Object, Object...)
.
withArguments(Object, Object...)
public static RequestSpecification given()
given().parameters("firstName", "John", "lastName", "Doe").expect().body("greeting.firstName", equalTo("John")).when().post("/greetXML");will send a POST request to "/greetXML" with request parameters firstName=John and lastName=Doe and expect that the response body containing JSON or XML firstName equal to John. The only difference between
with()
and given()
is syntactical.
public static RequestSender given(RequestSpecification requestSpecification, ResponseSpecification responseSpecification)
RequestSpecification requestSpecification = with().parameters("firstName", "John", "lastName", "Doe"); ResponseSpecification responseSpecification = expect().body("greeting", equalTo("Greetings John Doe")); given(requestSpecification, responseSpecification).get("/greet");This will perform a GET request to "/greet" and verify it according to the
responseSpecification
.
public static Response get(String path, Object... pathParams)
path
. Normally the path doesn't have to be fully-qualified e.g. you don't need to
specify the path as http://localhost:8080/path. In this case it's enough to use /path.
path
- The path to send the request to.pathParams
- The path parameters. E.g. if path is "/book/{hotelId}/{roomNumber}" you can do get("/book/{hotelName}/{roomNumber}", "Hotels R Us", 22);
.
public static Response get(String path, Map<String,?> pathParams)
path
. Normally the path doesn't have to be fully-qualified e.g. you don't need to
specify the path as http://localhost:8080/path. In this case it's enough to use /path.
path
- The path to send the request to.pathParams
- The path parameters.
public static Response post(String path, Object... pathParams)
path
. Normally the path doesn't have to be fully-qualified e.g. you don't need to
specify the path as http://localhost:8080/path. In this case it's enough to use /path.
path
- The path to send the request to.pathParams
- The path parameters. E.g. if path is "/book/{hotelId}/{roomNumber}" you can do post("/book/{hotelName}/{roomNumber}", "Hotels R Us", 22);
.
public static Response post(String path, Map<String,?> pathParams)
path
. Normally the path doesn't have to be fully-qualified e.g. you don't need to
specify the path as http://localhost:8080/path. In this case it's enough to use /path.
path
- The path to send the request to.pathParams
- The path parameters.
public static Response put(String path, Object... pathParams)
path
. Normally the path doesn't have to be fully-qualified e.g. you don't need to
specify the path as http://localhost:8080/path. In this case it's enough to use /path.
path
- The path to send the request to.pathParams
- The path parameters. E.g. if path is "/book/{hotelId}/{roomNumber}" you can do put("/book/{hotelName}/{roomNumber}", "Hotels R Us", 22);
.
public static Response delete(String path, Object... pathParams)
path
. Normally the path doesn't have to be fully-qualified e.g. you don't need to
specify the path as http://localhost:8080/path. In this case it's enough to use /path.
path
- The path to send the request to.pathParams
- The path parameters. E.g. if path is "/book/{hotelId}/{roomNumber}" you can do delete("/book/{hotelName}/{roomNumber}", "Hotels R Us", 22);
.
public static Response delete(String path, Map<String,?> pathParams)
path
. Normally the path doesn't have to be fully-qualified e.g. you don't need to
specify the path as http://localhost:8080/path. In this case it's enough to use /path.
path
- The path to send the request to.pathParams
- The path parameters.
public static Response head(String path, Object... pathParams)
path
. Normally the path doesn't have to be fully-qualified e.g. you don't need to
specify the path as http://localhost:8080/path. In this case it's enough to use /path.
path
- The path to send the request to.pathParams
- The path parameters. E.g. if path is "/book/{hotelId}/{roomNumber}" you can do head("/book/{hotelName}/{roomNumber}", "Hotels R Us", 22);
.
public static Response head(String path, Map<String,?> pathParams)
path
. Normally the path doesn't have to be fully-qualified e.g. you don't need to
specify the path as http://localhost:8080/path. In this case it's enough to use /path.
path
- The path to send the request to.pathParams
- The path parameters.
public static AuthenticationScheme basic(String userName, String password)
userName
- The user name.password
- The password.
public static AuthenticationScheme form(String userName, String password)
Note that the request will be much faster if you also supply a form auth configuration.
userName
- The user name.password
- The password.
form(String, String, com.jayway.restassured.authentication.FormAuthConfig)
public static AuthenticationScheme form(String userName, String password, FormAuthConfig config)
userName
- The user name.password
- The password.config
- The form authentication config
public static PreemptiveAuthProvider preemptive()
public static AuthenticationScheme certificate(String certURL, String password)
Class.getResource(String)
for how to get a URL from a resource on the classpath.
certURL
- URL to a JKS keystore where the certificate is stored.password
- password to decrypt the keystore
public static AuthenticationScheme digest(String userName, String password)
userName
- The user name.password
- The password.
public static AuthenticationScheme oauth(String consumerKey, String consumerSecret, String accessToken, String secretToken)
consumerKey
- consumerSecret
- accessToken
- secretToken
-
public static void registerParser(String contentType, Parser parser)
expect().body("document.child", equalsTo("something"))..Since application/vnd.uoml+xml is not registered to be processed by the XML parser by default you need to explicitly tell REST Assured to use this parser before making the request:
RestAssured.registerParser("application/vnd.uoml+xml, Parser.XML");
contentType
- The content-type to registerparser
- The parser to use when verifying the response.public static void unregisterParser(String contentType)
contentType
- The content-type associated with the parser to unregister.public static void reset()
baseURI
, basePath
, port
, authentication
and rootPath
, requestContentType(com.jayway.restassured.http.ContentType)
,
responseContentType(com.jayway.restassured.http.ContentType)
, filters(java.util.List)
, requestSpecification
, responseSpecification
. keystore(String, String)
,
urlEncodingEnabled
, config
and sessionId
to their default values of "http://localhost", "", 8080, no authentication
, "", null
, null
,
"empty list", null
, null
, none
, true
, null
, null
|
||||||||||
PREV CLASS NEXT CLASS | FRAMES NO FRAMES | |||||||||
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |