REST ASSURED TEST creating my own given() method - java

I have more than two similar REST ASSURED rests e.g.
#Test
public void makeSureThatGoogleIsUp() {
given().auth().oauth2(getToken()).contentType("application/json")
.when()
.get("http://www.google.com")
.then()
.statusCode(200);
}
#Test
public void makeSureThatGoogleIsUp() {
given().auth().oauth2(getToken()).contentType("application/json")
.when()
.get("https://stackoverflow.com")
.then()
.statusCode(200);
}
And I would've like to create method called given() to make method less complex and readable.
private [something] given(){
return given().auth().oauth2(getToken()).contentType("application/json")
}
making my methods use my given instead of rest assured one:
#Test
public void makeSureThatGoogleIsUp() {
given()
.when()
.get("http://www.google.com")
.then()
.statusCode(200);
}
#Test
public void makeSureThatGoogleIsUp() {
given()
.when()
.get("https://stackoverflow.com")
.then()
.statusCode(200);
}
something like here: but I dont really know what kind of return type this method could have or if its even possible.
Sorry, question can be trival, but seriously I'm stuck here.
Any helps? Thanks! :)

It returns a RequestSpecification object: http://static.javadoc.io/com.jayway.restassured/rest-assured/2.4.1/com/jayway/restassured/specification/RequestSpecification.html
Also a side note if you're creating your own given() -- it might be better to name the method something else as someone else using it might assume it's the jayway version and confuse themselves when they get errors.

Related

what is the usage of pathParam instead of full path in restAssured

According to this question I understand that pathParam is parameter for path in query.
But I don't understand what is the usage of that instead of writing the full path in get query like this if we have only one path anyway?
given().
baseUri("https://postman-echo.com")
.pathParam("userId", "1")
.when()
.get("/api/users/{userId}")
.then()
.log().ifError()
.assertThat()
.statusCode(200)
You could have your spec preserved and reuse parameter in different apis like:
public static void main(String[] args) {
RequestSpecification spec = given().
baseUri("https://httpbin.org/anything")
.pathParam("param", "123");
spec
.get("/api1/{param}")
.then()
.log().body();
spec
.get("/api2/{param}")
.then()
.log().body();
}

ServerResponseFilter not being applied to GET

I have a Quarkus application with the following filters definition:
#ApplicationScoped
#Slf4j
public class Filters {
// some #Inject parameters i'm using
#ServerRequestFilter(preMatching = true)
public void requestLoggingFilter(ContainerRequestContext requestContext) {
log.info("Recv: [{}] {}, {}", requestContext.getHeaderString("myHeader"), requestContext.getMethod(), requestContext.getUriInfo().getRequestUri());
}
#ServerResponseFilter
public void responseBasicHeaderFilter(ContainerResponseContext responseContext) {
responseContext.getHeaders().putSingle("myHeader, "myValue");
}
#ServerResponseFilter
public void responseLoggingFilter(ContainerResponseContext responseContext) {
log.info("Sent: [{}] {} {}", responseContext.getHeaderString("myHeader"), , responseContext.getStatusInfo(), responseContext.getEntity());
}
}
And I have two tests:
Test Class config:
#QuarkusTest
public class MyTest {
...
}
Test A:
final Response response = given()
.post(BASE_URL)
.then()
.extract().response();
assertEquals(200, response.getStatusCode(), () -> "Got: " + response.prettyPrint());
assertEquals("myValue", response.getHeader("myHeader"));
final Response response2 = given()
.get(BASE_URL)
.then()
.extract().response();
assertEquals(200, response2.getStatusCode(), () -> "Got: " + response2.prettyPrint());
assertEquals("myValue", response2.getHeader("myHeader"));
Test B:
final Response response = given()
.post(BASE_URL)
.then()
.extract().response();
assertEquals(200, response.getStatusCode(), () -> "Got: " + response.prettyPrint());
assertEquals("myValue", response.getHeader("myHeader"));
If i run Test B on it's own, it passes.
If i run Test A however the last assertion fails (the header value is not there).
The #ServerResponseFilter seem to not be called beyond the first time, however #ServerRequestFilter seem to be fine.
I have tested the api manually and can confirm the same behaviour. Calling the GET request first will also have the same behaviour.
I have verified that the response generated by my Controller (pojo) is generated successfully.
What could be preventing it from being rerun?
Turns out it wasn't related to GET vs POST
my GET method was returning a Multi . I converted this to Uni> and it worked.
From the documentation i found this snippet
Reactive developers may wonder why we can't return a stream of fruits directly. It tends to eb a bad idea with a database....
The keyword being we can't so I imagine this is not supported functionality

Cannot validate email values in restapi using restassured

can someone please assist, I'm using restassured to pull and display results from this server https://jsonplaceholder.typicode.com/posts/9/comments, but cannot verify the emails of this user and display accurate data. Here is my code below:
public static void getPostComments() {
System.out.println("===============Comments By User==================");
given().when().get(url + "/posts/9/comments").then().log()
.body();
Response res = given().when().get(url + "/posts/9/comments");
List<String> jsonRes = res.jsonPath().getList("email");
if (jsonRes.equals("Lucio#gladys.tv")) {
given().queryParam("id", "9")
.get("http://localhost:3000/posts/9/comments/")
.then()
.assertThat()
.body("email["+String.valueOf(0)+"]", Is.is("Lucio#gladys.tv"))
.log()
.body();
}
}
The results I get from the above code, just returns all the users without validating. I'm fairly new to restassured, but would appreciate any pointers to validate these emails.
There are many ways to do that.
Example 1:
given()
.get("https://jsonplaceholder.typicode.com/posts/9/comments")
.then()
.assertThat()
.body("email", hasItem("Lucio#gladys.tv"));
Example 2:
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasItem;
List<String> emails = given()
.get("https://jsonplaceholder.typicode.com/posts/9/comments")
.jsonPath()
.get("email");
assertThat(emails, hasItem("Lucio#gladys.tv"));

Quarkus PanacheEntity not saved during tests

I'm experimenting with Quarkus and Quarkus testing with RestEasy and I'm running into an issue while setting up dummy data before each of the tests.
I'm trying to insert a User using the Active Record pattern before calling the endpoint. Right after calling user.persistAndFlush() (or simply just calling .persist()) when the asking the User entity for the count of the users, it correctly gives back that there is one record in the database. However, when calling the endpoint through RestEasy, it throws back to me that the user is not found with that given identifier and indeed, when logging out the number of users in that certain method call in the service, there are 0 users according to Quarkus.
It looks to me as if the method with the #Test annotation and the service itself were running in a different context? It's a bit strange and I'm sure missing something obvious.
Here's what my test class looks like:
#QuarkusTest
#QuarkusTestResource(PostgreSQLDatabaseResource.class)
public class AuthenticationResourceTest {
#TestHTTPEndpoint(AuthenticationResource.class)
#TestHTTPResource
URL url;
#BeforeEach
#Transactional
public void setUp() {
User.deleteAll();
}
#Test
public void testWithNonExistingEmail() {
AuthenticationChallenge invalidAuthRequest = AuthenticationChallenge.builder()
.email("admin#admin.com")
.password("something")
.build();
given()
.when()
.contentType(ContentType.JSON)
.body(invalidAuthRequest)
.post(url)
.then()
.statusCode(401);
}
#Test
#Transactional
public void testWithValidAuthenticationChallenge() {
User user = User.builder()
.name("admin")
.role(Roles.ADMIN)
.status(Status.ACTIVE)
.password(BCrypt.withDefaults().hashToString(10, "admin".toCharArray()))
.email("admin#admin.com")
.build();
user.persistAndFlush();
given()
.when()
.contentType(ContentType.JSON)
.body(AuthenticationChallenge.builder().email("admin#admin.com").password("admin").build())
.post(url)
.then()
.statusCode(200)
.log()
.all();
}
}
Your user won't be saved to the database until the end of the test method as it's transactional and the transaction is committed at the end.
With your REST call, you query your database outside of the transaction so you won't have the data.
If you want to initialize some data visible to your REST call, you need to create the data in the #BeforeEach method.

Asserting Rest Assured response with Json Unit

I'm currently using rest assured and Json-unit to assert a local json file against the requested rest assured response.
I currently have a before class method with my base uri.
I don't know how to make this assertion. I'm struggling with the json-unit documentation. Do I need to input a file first?
#Test
public void ApiaryTest1() throws Exception {
when()
.get("/test")
.then()
.statusCode(200);
// compares two JSON documents
assertJsonEquals("expected/test.json", "http://apiary/test");
}
You need to:
Read in the resource with the JsonUnit API
Extract the response from rest assured to a variable
Assert you are already doing
Example:
Response response = when().get("<url>");
response
.then()
.statusCode(200);
// compares two JSON documents
assertJsonEquals(resource("resource-inside-resources-folder.json"), response.asString());
For Restassured Kotlin DSL:
When {
get("http://nowjidev1vm01.ath.bskyb.com/calskyplussearch/health")
} Then {
statusCode(200)
} Extract {
assertJsonEquals(expectedBody, response().asString())
}
It is easier than you think. Rest Assures is passing the entire body as string in case of a "body matcher" is specified. Therefore you can just use the jsonEquals matcher of json unit directly:
import static net.javacrumbs.jsonunit.JsonMatchers.jsonEquals;
public class RestAssuredWithJsonUnit {
#Test
public void test() throws Exception {
given().when().get("/api/service/v1").
then().
statusCode(200).
body(jsonEquals(resource("resource-on-classpath.json")));
}
public static String resource(String resourceName) throws IOException {
Objects.requireNonNull(resourceName, "'null' passed instead of resource name");
return IOUtils.resourceToString(resourceName, UTF_8);
}
Please note the implementation of the "resource" method. The one provided in ResourceUtils is using the system classloader, which did not found my resoulces unfortunately. IOUtils from commons-io does the job well!

Categories

Resources