I want to mock response with payload as a simple string.
Below code is in my test :
Response response = mock(Response.class, RETURNS_DEEP_STUBS);
when(mockRestClient.get("someMockUrl")).thenReturn(response);
when(response.readEntity(String.class)).thenReturn("XXXYYYZZZ");
Also tried with:
Response response = Response.status(Status.OK).entity("XXXYYYZZZ").build();
MyCode looks something like this :
Response response = restClient.get(tokenUrl); // I was mocking this and getting mock response
String requestToken = response.readEntity(String.class); //failing at this line
None of the above is working.
Help is Appreciated!
I see the issue was with using the deep stubs. It was not necessary in my case.
Response mockResponse = mock(Response.class);
when(mockResponse.readEntity(String.class)).thenReturn("XXXYYYZZZ");
Related
I am trying to do a GET request and print the JSON response that I get back. The JSON response should look like this.
{
"request_status": "Success",
"workflow_step": "End"
}
Here's my code:
handle(GetStatus) { args: GetStatus.Args =>
val client: Service[http.Request, http.Response] =
Http.client.withTlsWithoutValidation.newService("idm-preprod-fe1.twitter.biz:80")
val request = http.Request(
http.Method.Get,
"/plugin/rest/groupmanagement/getStatus/Create Group Request for mygroup (1638800484991)")
request.host = "idm-preprod-fe1.twitter.biz"
Future.value(GetStatusResponse(Option(client(request).toString)))
}
Now when my client sends the request to the server, I want to print the JSON but the format that I am getting is. Can someone please guide me as how to achieve this.
Promise#1589131174(state=Transforming(WaitQueue(size=1),Promise#1823443423(state=Transforming(WaitQueue(size=1),Promise#859399396(state=Transforming(WaitQueue(size=4),Promise#1441370332(state=Transforming(WaitQueue(size=2),Promise#1459834(state=Transforming(WaitQueue(size=2),Promise#156947070(state=Transforming(WaitQueue(size=1),Promise#1739595981(state=Transforming(WaitQueue(size=1),Promise#273198152(state=Transforming(WaitQueue(size=1),Promise#478329071(state=Transforming(WaitQueue(size=2),Promise#1175786031(state=Transforming(WaitQueue(size=1),Promise#1749285277(state=Transforming(WaitQueue(size=1),Promise#1733124454(state=Transforming(WaitQueue(size=1),Promise#1257379837(state=Transforming(WaitQueue(size=1),Promise#1192050340(state=Transforming(WaitQueue(size=1),Promise#1114225943(state=Transforming(WaitQueue(size=1),Promise#1417620904(state=Transforming(WaitQueue(size=1),Promise#1638767611(state=Interruptible(WaitQueue(size=2),<function1>))))))))))))))))))))))))))))))))))
client(request) is giving you a Future[http.Response]: it represents a response that will be available some time in the future.
You cannot use toString() on it directly because it's a Future and also because even if it was not a Future it would be a Response, which is a whole HTTP response, not only the body.
I'd recommend reading more about how Future works and how to use it.
In your case, you should do something like following (pseudo code as I'm not familiar with Twitter's Future):
client(request).map { httpResponse =>
val responseBody = httpResponse.body
GetStatusResponse(Option(responseBody))
}
I have a REST API to callout from Salesforce.
The authorization of the API is through access token.
I am able to get the access token through POST request in Salesforce. Also tested from Postman through that token and able to get a successful response.
I am using the below code to callout the API using the access token:
String endpoint_x = '*****';//Putting my endpoint here
Http httpObject;
HttpResponse response;
String accessToken;
accessToken = MyUtilityClass.getAccessToken();
jsonBody = json.serializePretty('', true);//Yes, My JSON is empty
HttpRequest request = new HttpRequest();
request.setEndpoint(endpoint_x);
request.setHeader('Authorization', 'Bearer '+accessToken);
request.setMethod('POST');
request.setBody(jsonBody);
httpObject = new Http();
response = httpObject.send(request);
System.debug('Response=' + response);
Getting Response value as below:
System.HttpResponse[Status=Internal Server Error, StatusCode=500]
I have tried putting '{}' in the Jsonbody. Added 'Content-Type' in header but nothing worked.
Where should I lookout for this?
In the Postman, I was not putting anything in the body, and getting a successful response.
To get the same behaviour, I was using empty string in Apex, like this:
jsonBody = json.serializePretty('', true);
But the parser was not working correctly.
To solve this, I created a class without any field:
class ClassForEmptyBody{
}
And used object of that class in the serializer:
ClassForEmptyBody classForEmptyBodyObject = new ClassForEmptyBody();
jsonBody = json.serializePretty(classForEmptyBodyObject , true);
Why are you passing json body if nothing is in there. Just skip setbody code and try.
i have the follow function:
Future<Null> _loadORDER(String menssage) async {
var enZona =await ApiClient.zonaNum(menssage, apiKey);
print('enZona: $enZona');
if (enZona == 'true') {
_moveToNotification(context);
};
}
the print give me the follow message: "enZona: Instance of 'Response'"
if i test the response from postman of the api query is working normally and give me: true ,
then i hope that the print result will be : "enZona: true"
but i don't know how i do to wait the response of the ApiClient before continue with the conditional (if)
thanks for your help!
thanks i add the .body but i get the same response, the apiclient code is the follow:
final response = await http.get(baseUrl + '/shop/order/$message',
headers: {HttpHeaders.authorizationHeader: apiKey});
print("enZona: $response.body");
return response;
the print value for this is: enZona: Instance of 'Response'.body
You should do print("enZona: ${response.body}"); with the curly bracket, or you can assign response.body to some variable first.
final foo = response.body; print(foo);
If you go to the pub.dev documentation for the Response class, you will see that Response is more than the content of the response. It is a wrapper class that also includes information such as the statusCode of the response, the headers, etc.
When you saw the response in Postman, you only cared about the content of the response, that is, the body of the response. What you are looking for in your code is not the enZona instance of Response, but the body of the enZona response.
Therefore, you have to swap enZona by enZona.body when trying to access the contents of your response.
Am getting the response of a request like this:
var response = command.PostCommand(testCommand);
I will like to validate that the response is in a json format so am doing it like this:
Assert.AreEqual("application/json", response.ContentType);
Is this way correctly or do i need to specifically validate it from the content-type header response?
You can use the IRestRequest.OnBeforeDeserialization callback to check the response content type before it gets deserialised:
var request = new RestRequest(url)
.AddQueryParameter(x, y); // whatever you need to configure
request.OnBeforeDeserialization =
response => CheckContentType(response.ContentType);
await client.PostAsync<MyResponse>(request);
I am using Client() from http.dart. I am able to post with parameter but I have no idea how to do get with parameter. Post has body that takes the parameter but get doesn't.
I have tried
This is my client
Client httpClient = Client();
var response = await httpClient.get("controller/action/{parameter here}"
I hope this should solve your problem
fetchData() async {
Client httpClient = Client();
counter++;
var response =
await httpClient.get('https://jsonplaceholder.typicode.com/photos/$counter');
print(response.body);
}
i think you are saying that you want any kind of data to be sent to the server with GET request too,
you can not do it simply,
may be your parameter are the header of the Get ,
try passing your parameters in the header of GET