Validating empty restful response array using restassured - java

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
}

Related

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());

Why my list is empty when I am parsing correct json response?

I am trying to print the ids from a JSON response. But I am not able to understand why I am getting a blank list. I have verified the JSONpath (SECTIONS_IDS_JSONPATH) from the online website and it is giving me correct results.
public static void main(String[] args) {
String SECTIONS_IDS_JSONPATH = "$.[*].instructionEvents[*].sectionId";
String sectionsData = "{\"sections\":[{\"id\":\"8da1cf5d-3150-4e11-b2af-338d1df20475\",\"courseId\":\"e8a65581-ed1c-43f0-90a7-7b9d51b35062\",\"courseCredits\":[{\"minimum\":4,\"maximum\":null,\"measure\":\"hour\",\"increment\":null}],\"academicPeriodId\":\"8b7a8e9e-5417-42a3-9c90-8d47226b5987\",\"reservedSeatsMaximum\":0,\"maxEnrollment\":0,\"hours\":[],\"sites\":[\"All Campuses\"],\"instructors\":[],\"instructionEvents\":[{\"id\":\"9d0c49e2-1579-43c3-b25a-2f85f551e62d\",\"sectionId\":\"8da1cf5d-3150-4e11-b2af-338d1df20475\",\"courseId\":\"e8a65581-ed1c-43f0-90a7-7b9d51b35062\",\"days\":[\"monday\",\"wednesday\",\"friday\"],\"startTm\":\"2019-01-01T09:45:00-05:00\",\"endTm\":\"2024-12-01T10:45:00-05:00\",\"localizations\":[],\"instructionalMethod\":\"Lecture\"}]},{\"id\":\"ad3f63ad-e642-4938-a9fd-318afd2d1ad0\",\"courseId\":\"e8a65581-ed1c-43f0-90a7-7b9d51b35062\",\"courseCredits\":[{\"minimum\":4,\"maximum\":null,\"measure\":\"hour\",\"increment\":null}],\"academicPeriodId\":\"8b7a8e9e-5417-42a3-9c90-8d47226b5987\",\"reservedSeatsMaximum\":0,\"maxEnrollment\":20,\"hours\":[],\"sites\":[\"All Campuses\"],\"instructors\":[{\"id\":\"c26572de-f9c8-4623-ba6a-79997b33f1c6\",\"sectionId\":\"ad3f63ad-e642-4938-a9fd-318afd2d1ad0\",\"role\":\"primary\",\"persons\":[{\"id\":\"c1b50d79-5505-4a33-9316-b4b1f52c0ca3\",\"names\":[{\"firstName\":\"BanColoFac-1\",\"lastName\":\"CTester\",\"preferred\":true}]}]}],\"instructionEvents\":[{\"id\":\"af8fb500-29f5-4451-95d5-a11215298cd4\",\"sectionId\":\"ad3f63ad-e642-4938-a9fd-318afd2d1ad0\",\"courseId\":\"e8a65581-ed1c-43f0-90a7-7b9d51b35062\",\"days\":[\"tuesday\",\"thursday\"],\"startTm\":\"2019-01-01T10:00:00-05:00\",\"endTm\":\"2024-12-01T10:50:00-05:00\",\"localizations\":[],\"instructionalMethod\":\"Lecture\"}]},{\"id\":\"a1422391-e2b9-4bc4-907b-371fcea01d70\",\"courseId\":\"e8a65581-ed1c-43f0-90a7-7b9d51b35062\",\"courseCredits\":[{\"minimum\":4,\"maximum\":null,\"measure\":\"hour\",\"increment\":null}],\"academicPeriodId\":\"8b7a8e9e-5417-42a3-9c90-8d47226b5987\",\"reservedSeatsMaximum\":0,\"maxEnrollment\":20,\"hours\":[],\"sites\":[\"All Campuses\"],\"instructors\":[{\"id\":\"808daae1-3ec6-47ec-9af0-5392199bdf78\",\"sectionId\":\"a1422391-e2b9-4bc4-907b-371fcea01d70\",\"role\":\"primary\",\"persons\":[{\"id\":\"793cc9b3-57c7-4a2d-8984-07a1fb6834a9\",\"names\":[{\"firstName\":\"Andrew\",\"lastName\":\"Adams\",\"preferred\":true}]}]}],\"instructionEvents\":[{\"id\":\"730b4206-684d-4413-bf20-9bec5c1dc900\",\"sectionId\":\"a1422391-e2b9-4bc4-907b-371fcea01d70\",\"courseId\":\"e8a65581-ed1c-43f0-90a7-7b9d51b35062\",\"days\":[\"tuesday\",\"thursday\"],\"startTm\":\"2019-01-01T10:00:00-05:00\",\"endTm\":\"2024-12-01T10:50:00-05:00\",\"localizations\":[],\"instructionalMethod\":\"Lecture\"},{\"id\":\"8bc059ab-a8f8-4469-8e79-bbc71f7fa3fd\",\"sectionId\":\"a1422391-e2b9-4bc4-907b-371fcea01d70\",\"courseId\":\"e8a65581-ed1c-43f0-90a7-7b9d51b35062\",\"days\":[\"monday\",\"wednesday\",\"friday\"],\"startTm\":\"2019-05-26T09:00:00-04:00\",\"endTm\":\"2021-05-26T09:50:00-04:00\",\"localizations\":[],\"instructionalMethod\":\"Lecture\"}]}]}";
List<String> ids = JsonPath.parse(sectionsData).read(SECTIONS_IDS_JSONPATH);
System.out.println(ids);
}
Alright, since this question might get delete if nothing else ever happens I better post this as an answer.
As explained by Andreas you should use JSONPath $.*[*].instructionEvents[*].sectionId instead. Quoting fromt the comment
The syntax $.[*] is undefined, I can't find any documentation/example
doing that. The JSONPath Online Evaluator [*based on
JSONPath-Plus implemented in JavaScript] treats it as $..[*], but the Java library treats
it differently. Since the outer part of the JSON is {"sections":[ ... ]}, you have an object, so you need a property selector (.prop or
.*). Once you've selected your property (.sections, or .*
since there's only one), the property is an array, so you need an
array selector ([2] or [*]). Hence you can use $.sections[*] or
$.*[*] to match all sections.
Indeed, looking at this massive JSONPath Comparision we can see that the syntax in question is not listed for any implementation.

How can I use loop for JSON request/response with multiple similar parameters in Java?

Is there a way to put my request, and use my response in a loop when I've got very similar values? I thought about for loop but can't find a way to implement this.
I'm sending a request from Android device and there are TextView waiting for a response. When I got my response, I'm checking if it is not empty or null and if it's not, I'm setting text of TextView and changing visibility(because the default is gone).
For example this would be my JSON.
{
spaghetti: [
{
strIngredient1: "1 pound ground beef",
strIngredient2: "1 onion, chopped",
strIngredient3: "null",
strIngredient4: "1 (28 ounce) can diced tomatoes",
strIngredient5: ""
}
]
}
And my condition:
if(!"".equals(dinner.getStrIngredient1()) && !"null".equals(dish.getStrIngredient1())) {
firstIngredient.setText(dinner.getStrIngredient1());
firstIngredient.setVisibility(View.VISIBLE);
}
if(!"".equals(dinner.getStrIngredient2()) && !"null".equals(dish.getStrIngredient2())) {
secondIngredient.setText(dinner.getStrIngredient2());
secondngredient.setVisibility(View.VISIBLE);
}
...
As you can see above, I've got similar values and do I really need to repeat it five times? Is there way to make it "clean"?
I think yes, or you can use switch case, But writings would be there so same.
Use java Reflection.
But for that you need to tweak your firstIngredient, secondIngredient naming to ingredient1, ingredient2 respectively.
Get a for loop over your arraylist of Ingredients
Then use java reflection to form method dynamically
Method method = obj.getClass().getMethod(methodName);//in methodname you can write method you like to invoke like ingredient+i
method.invoke(obj, arg1, arg2);

how to list all the indices' name of elasticsearch using java?

In my elasticsearch I want to get all the indices' name of the cluster. How can I do using java?
I search the internet but there's no much useful information.
You can definitely do it with the following simple Java code:
List<IndexMetaData> indices = client.admin().cluster()
.prepareState().get().getState()
.getMetaData().getIndices();
The list you obtain contains the details on all the indices available in your ES cluster.
You can use:
client.admin().indices().prepareGetIndex().setFeatures().get().getIndices();
Use setFeatures() without parameter to just get index name. Otherwise, other data, such as MAPPINGS and SETTINGS of index, will also be returned by default.
Thanks for #Val's answer. According to your method, I use it in my projects, the code is:
ClusterStateResponse response = transportClient.admin().cluster() .prepareState()
.execute().actionGet();
String[] indices=response.getState().getMetaData().getConcreteAllIndices();
This method can put all the indices name into a String array. The method works.
there's another method I think but not tried:
ImmutableOpenMap<String, MappingMetaData> mappings = node.client().admin().cluster()
.prepareState().execute().actionGet().getState().‌getMetaData().getIndices().
then, we can get the keys of mappings to get all the indices.
Thanks again!

Rest Assured Empty response body structure

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.

Categories

Resources