I am trying to implement a test of my rest api using restsharp, which seems to be a very powerful and easy tool to use for simple tests.
With that said I still have problems getting content from my IRestResponse.
The code goes as following:
...
[TestMethod]
public void Testing_Whether_Get_Returns_cellphone()
{
// Arrange
RestClient restClient = new RestClient("http://pseudoUrl/Users?UserId={uid}");
//restClient.AddDefaultHeader("headerType1", Guid.NewGuid().ToString());
//restClient.AddDefaultUrlSegment("uid", "25248896");
RestRequest restRequest = new RestRequest(Method.GET);
restRequest.AddQueryParameter("uid", "25248896");
restRequest.AddHeader("headerType1", Guid.NewGuid().ToString());
// Act
IRestResponse restResponse = restClient.Execute(restRequest); // restresponse = "StatusCode: Ok.."
string response = restResponse.Content; // response = "[]"
// Assert
Assert.IsTrue(response.Contains("cellphone"));
}
...
When testing the above, the statuscode is 200, but content is "[]", even though that when I test it with swagger, I get a nice json-response filled with the wanted content.
As you can see I have tried using both AddDefaultUrlSegment and AddQueryParameter. The last one is the most obvious, I guess?
the following url in swagger is: " http://pseudoUrl/Users?UserId=25248896 " added the header: headerType1 and again - that works perfectly fine.
Can anyone see, what I am doing wrong?
AddQueryParameter
with your current inputs is going to add ?uid=25248896
to the URL.
Just put your URL without query http://pseudoUrl/Users
into the RestClient
constructor and then change the "uid" to "UserId" in AddQueryParameter
[TestMethod]
public void Testing_Whether_Get_Returns_cellphone()
{
// Arrange
RestClient restClient = new RestClient("http://pseudoUrl/Users");
RestRequest restRequest = new RestRequest(Method.GET);
restRequest.AddQueryParameter("UserId", "25248896");
restRequest.AddHeader("headerType1", Guid.NewGuid().ToString());
// Act
IRestResponse restResponse = restClient.Execute(restRequest);
string response = restResponse.Content; // response = "[]"
// Assert
Assert.IsTrue(response.Contains("cellphone"));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.