Rest Assured Empty response body structure - java

I'd like to test a find rest service, if I find smth I want to delete from the database, otherwise do nothing
I use it like this (where rs is the Response from find)
JsonPath jsonPath = rs.getBody().jsonPath();
Object foundName= jsonPath.get("name");
if (foundName!= null) {
expect().statusCode(200).when().delete("..." + foundName);
}
So when nothing is found how to check the foundName for it , because I tried foundName!=null or foundName != "", and still it's not working.
So please explain what is the structure of an empty response body

Based on the debug info foundName is of type List , so the solution was to cast foundName to List and check if it's empty.
List foundName = (List)jsonPath.get("name");
foundName.isEmpty()

rs.body(blankOrNullString());
worked for me to verify the response body is null or blank.

You could call jsonPath.getString("name") which casts your (empty) response body to String and you could check it with equals("") (see RESTassured JavaDoc). I assumed that "name" is of type String.

Related

RestTemplate postForEntity return List of DTO

im working ina spring project and using restemplate to call POST API that take a List of DTOOne And return a List of DTOTWO.
this is my code :
List<MYDTOONE> listDTORequest;
//values..
ResponseEntity<List<MYDTOOTWO>> userActionsResponse = restTemplate.postForEntity("my yrl",
listDTORequest, MYDTOOTWO.class);
im geeting a Syntax error in the last param i need to know how i can tell postForEntity that im waiting for List.
i tried also List<MYDTOOTWO> in the last paramater but still syntax error
thanks in advance.
You can try to use the following new ParameterizedTypeReference<List< MyDtoTwo>>() {} instead of MYDTOOTWO.class (MyDtoTwo written for ease of reading) with the exchange method (UPDATE: postForEntity has parameterizedTypeReference removed).
What happens in your case is the response you get back is parsed as MYDTOOTWO.class however you're trying to interpret the result as a list, resulting in a mismatch. With parameterized type reference, you can specify that you're expecting a list of MYDTOOTWO.class instead.
Your call should be:
ResponseEntity<List<MYDTOOTWO>> userActionsResponse = exchange("my yrl", HttpMethod.POST,
listDTORequest, new ParameterizedTypeReference<List< MYDTOOTWO>>() {});
List<MYDTOTWO> body = userActionsResponse.getBody();
UPDATE (as suggested by OP):
If you notice, you will need to send the HttpMethod.POST when making a POST request (as the second argument) and wrap your headers and request data in an HttpEntity requestEntity object as follows:
HttpEntity<Object> requestEntity = new HttpEntity<>(listDTORequest, headers);
It may not be the cleanest code, but it is the fastest and simplest way I have found to do it. You read it as an Array and then put it in the List.
List<MYDTOONE> listDTORequest;
// JDK8
List<MYDTOOTWO> userActionsResponse = Arrays.asList(restTemplate.postForEntity("my url", listDTORequest, MYDTOOTWO[].class).getBody());
// JDK9+
List<MYDTOOTWO> userActionsResponse = List.of(restTemplate.postForEntity("my url", listDTORequest, MYDTOOTWO[].class).getBody());

How to handle response with <?> type in spring-boot?

There is some third-party function with a method signature.
public ResponseEntity<?> uploadFile()
Without going into too much detail, this function uploads a file and returns a json response back, with a field containing the word ok.
I know the DTO structure that the function returns when the file is successfully uploaded.
But how do I handle a negative outcome. When does the error return? This example is abstract. But it can be understood that the structure of the erroneous DTO is not equal to the structure of the DTO on a positive outcome.
And I somehow need to check this field, let's call it "status", that it is not null. How can this be done better?
You can cast the response to String type first.
For example - ResponseEntity<String> resp = uploadfile();
Then check the status code for the response.
I am assuming that you will be getting 2xx series for a successful file upload and 4xx series if there is a failure.
Based on the status code you can conditionally map the string response body to whichever DTO you want to map it to.
For ex :
if(resp.getStatusCode()==200) {
SuccessDTO s= new
ObjectMapper().readValue(resp.getBody(),SuccessDTO.class);
}
else
{
ErrorDTO s= new
ObjectMapper().readValue(resp.getBody(),ErrorDTO.class);
}

mockMvc assert that content is null (content is not json)

I want to assert that the returned content (model and view) are both null on certain conditions but I can't find the right Matcher. Could someone please show me how this should be done? If this problem was solved in another thread I apologize I could not find it.
mockMvc.perform(get("/test")
.headers(assembleBasicAuthHeader("idontexist", "gibberish")))
.andExpect(status().isForbidden())
.andExpect(content().isNull()) //this obviously doesnt work
.andExpect(model().isNull()) //this obviously doesnt work
.andExpect(status().reason(containsString("Forbidden")));
Assuming your API supports JSON (it's not clear from your question), one way would be to assert the response body using JSON path expressions:
mockMvc.perform(get(..)
.headers(..)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isForbidden())
.andExpect(status().reason(..))
.andExpect(jsonPath("$").doesNotExist());

Getting the value from the response element using GPath and Rest Assured

I want to get the value of status from my response. So that i can assert it. I'm using rest assured with java & serenity BDD.
Response
{
"locationType": "STORE",
"locationId": "0003",
"events": {
"66e326db-fbfb-4f6e-9d2b-9425e7test5": {
"status": "BOOKING_OPEN"
}
}
}
So, here the event id (66e326db-fbfb-4f6e-9d2b-9425e7test5) is dynamic, which means for each run this UUID will get change.
Code
Response response = SerenityRest.lastResponse();
final ValidatableResponse validatableResponse = response.then();
validatableResponse.assertThat().body("events.*.status", containsString(expectedResponse));
When i run this, i'm getting Unrecognized Exception from serenity BDD. I think, that there is some issue in traversing in JSON.
Can someone please help me on getting the value of status here? So in this case, i'm looking for
BOOKING_OPEN
I think you should store UUID as a variable, and change your locator from your response.
response.getBody().jsonPath().get("events."+yourUUID+".status");
Groovy JsonSlurper does not support * breadthFirst() or ** depthFirst() tokens.
You could use below one to get the String result:
response.getBody().jsonPath().get("events.collect{it.value.status}.find()");
// would return "BOOKING_OPEN"
or below one to get a List result:
response.getBody().jsonPath().get("events.collect{it.value.status}");
//would return ["BOOKING_OPEN"]

Validating empty restful response array using restassured

Sometimes GET call is returning [] empty array. I can use .body(size), but I do not want to use hard assertions.
It can be empty or have an array of objects, so I want to use if condition to make a decision to proceed further based on empty/not empty.
The code is as below:
given().when().get(url).then().body("[0].name",equalTo(value‌​))
Any help would be appreciated.
you can try with the below way
Response res = given().when().get(url);
if(!(res.body().asString().equals("null"))
{
// do what you want to check or action
}

Categories

Resources