REST-ASSURED posting empty request body for generated object - java

I'm using rest assured to send a post with a generated body from a model class. The model class uses the builder pattern and I confirmed that it is getting built correctly:
Request body:
McpSalesInvoicesPost(invoices=[McpSalesInvoices(type=PRE_ORDER, amount=212.0, currencyCode=INR, transactionDate=2020-10-24T22:43:24, payments=[McpSalesPayments(type=CASH, amount=212.0, currencyCode=INR, reference=reference text sample 376, transactionDate=2014-08-20T19:23:51)])])
When I use that object in the rest assured post call I get an empty body in the request. Here is the rest assured code:
response = SerenityRest
.given()
.filters(Arrays.asList(new RequestLoggingFilter(), new ResponseLoggingFilter()))
.contentType(ContentType.JSON)
.header(new Header("x-openapi-clientid", "client-id-1"))
.body(requestBody)
.when()
.request(verb, SALES_BASE_URL + endpoint);
where request body is the built object mentioned above and this gives:
Body:
{
}
for the request. Any ideas on where I'm going wrong?
A

Maybe try .with().body(object).
response = SerenityRest
.given()
.filters(Arrays.asList(new RequestLoggingFilter(), new ResponseLoggingFilter()))
.contentType(ContentType.JSON)
.header(new Header("x-openapi-clientid", "client-id-1")).with().
.body(requestBody)
.when()
.request(verb, SALES_BASE_URL + endpoint);

Related

Get Cookie By name after a restTemplate call

I'm sending a request ro a service that set a cookie in the response :
HttpEntity<String> response = restTemplate.exchange
(myUrl,
HttpMethod.GET,
new HttpEntity<>(headers),
String.class);
I found that I can extract the cookie using this line of code :
String set_cookie = response.getHeaders().getFirst(HttpHeaders.SET_COOKIE);
However this returns: name_of_cookie=value_of_cookie
I know that I can make a String processing to extract the value of the cookie by name, but I want to find a better solution in the manner of :
response.getHeaders().getCookieValueByName(cookie_name)
The getCookieValueByName function do not exsist. Is there a function that does what I want to do ?

the difference between Postman and POST request in Java

I need to get some respones from some URL.
For this purpose I use http://unirest.io/java.html and Java.
Map<String, String> map = new HashMap<>();
map.put(key1, value1);
...
map.put(keyN, valueN);
String authToken = "{token}";
HttpResponse<String> response = Unirest.post(url)
.header("Authorization","Bearer " + authToken)
.header("Content-Type", "application/json")
.fields(map)
.asString();
As a result I receive response.getStatus() = 302 and some unexpected body.
At the same time I use Postman software to get the same responses. The settings are the following:
POST: url
Authorization: Type -> Bearer Token; Token = {{authToken}} // get the value from the previous request
Header :
"Authorization" : "Bearer " + {{authToken}}
Content-Type: application/json
Body:
{
key1 : value1,
...
keyN : valueN
}
And I get some expected response.
What makes the difference?
A 302 is a redirect response. Is it possible Postman is following the redirect and returning the resultant page? Take a look at the Location header in the response you get in Java, and see if following that gives you the same results you're seeing in Postman.

How to write Mock test cases for Webtarget and Response for a rest client?

WebTarget resource = clientLocal.target(/test/url))
Response response = resource.request(MediaType.APPLICATION_JSON)
.header("Content-type", MediaType.APPLICATION_JSON)
.header("Authorization", "Basic"+" "+"234YML")
.post(Entity.entity("", MediaType.TEXT_PLAIN), Response.class);
responseEntity = response.readEntity(Test.class);
When Response object is mocked, builder object for Authorization header is returning null,
Mockito.when(mockWebTarget.request(MediaType.APPLICATION_JSON)).thenReturn(mockBuilder);
Mockito.when(mockBuilder.header("Content-type", MediaType.APPLICATION_JSON))
.thenReturn(mockBuilder);
Mockito.when(mockBuilder.header("Authorization",eq(anyString())))
.thenReturn(mockBuilder);
Mockito.when(mockBuilder.post(Entity.entity(anyString(), MediaType.TEXT_PLAIN), eq(Response.class)))
.thenReturn(mockResponse);
How the second part of header should be mocked so that it does not return null value?
eq(anyString()) is the problem in
Mockito.when(mockBuilder.header("Authorization",eq(anyString())))
.thenReturn(mockBuilder);
It should be
Mockito.when(mockBuilder.header(eq("Authorization"), anyString()))
.thenReturn(mockBuilder);
The argument matcher eq is used for literal matches.
Also if you are using argument matchers, all arguments have to be provided by matchers.
The first one worked because all the arguments were literal values.
That would also mean that
Mockito.when(mockBuilder.post(Entity.entity(anyString(), MediaType.TEXT_PLAIN), eq(Response.class)))
.thenReturn(mockResponse);
needs to change to
Mockito.when(mockBuilder.post(any(Entity.class), eq(Response.class)))
.thenReturn(mockResponse);

Java - Neo4J Rest call to put labels to nodes

I've been trying to place labels over newly created nodes using Neo4J restful api. The following is the CURL request I've tried.
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://localhost:7474/db/data/");
String propertyUri_labels = "http://localhost:7474/db/data/node/9/labels";
Response response = target
.path(propertyUri_labels)
.request(MediaType.APPLICATION_JSON)
.header("application/xml", "true")
.accept(MediaType.APPLICATION_JSON)
.put(Entity.entity("\"" + "Artist" + "\"", MediaType.APPLICATION_JSON_TYPE));
System.out.println( String.format( "PUT to [%s], status code [%d]",
propertyUri_labels, response.getStatus() ) );
However, I have not been successful and got an status code [400]. Is there something wrong with my URL "http://localhost:7474/db/data/node/9/labels" ?
Pls help.
Thanks!
Try a POST instead of PUT.
Check the documentation => http://neo4j.com/docs/rest-docs/current/#rest-api-node-labels

java rest client for mixed parameter forms

I have a rest method which takes two parameters one map parameter, and the other is a String variable
#POST
public returnValue postMethod( Map<String,String> anotherMap,
#QueryParam("name") String name
) {}
It is easy to pass each parameter by itself where
the map parameter can be passed using XML as follow :
ClientResponse response = service
.type(MediaType.APPLICATION_XML)
.accept(MediaType.APPLICATION_XML)
.post(ClientResponse.class, map).getEntity(ClientResponse.class).
and the QueryParam can be passed as usual :
service.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE)
.accept(MediaType.APPLICATION_JSON_TYPE)
.post(ClientResponse.class, f)
where f is a Form ,
the question is : how can we pass both parameter together from the same Java client ?
So you're asking - how do I POST a Map and pass a String as a query param? With sending and receiving XML.
Here's how I'd do it:
ClientBuilder clientBuilder = ClientBuilder.newBuilder();
//Do some building code
Client client = clientBuilder.build();
WebTarget target = client.target(endPoint);
Response response = target
.queryParam("name", "value")
.request(MediaType.APPLICATION_XML_TYPE)
.post(Entity.entity(map), MediaType.APPLICATION_XML_TYPE);
Hope this helps.

Categories

Resources