I was trying to put an assert for Response Code for my request, but i am having hard time to figure out, could you please help me on this. Here is my implementation and definition.
myTests.cs
var accessToken = await helper.SendRequestAsync<AccessToken>(baseUrl, body);
==> how to set assert here right after above statement to verify response status?
helpers.cs
public static async Task<T> SendRequestAsync<T>(string baseUrl, Dictionary<string, string> body)
{
using (var flurl_client = new FlurlClient(baseurl))
{
try
{
var response = await flurl_client
.Request()
.PostUrlEncodedAsync(body)
.ReceiveJson<T>();
return response;
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
return default(T);
}
}
======================================================
Data model for "AccessToken" is in Dto.cs
public class AccessToken
{
public string token_type { get; set; }
public string expires_in { get; set; }
public string ext_expires_in { get; set; }
public string expires_on { get; set; }
public string not_before { get; set; }
public string resource { get; set; }
public string access_token { get; set; }
public string refresh_token { get; set; }
public object Status_Code { get; set; }
}
If you're you looking for Flurl's testing features to help with this, I'm afraid it won't work. Those features are specifically designed for testing the behavior of your client-side code based on fake responses that you set up in your test. It looks like you want to assert the status code from a real call.
The best way I can think of is to drop the .ReceiveJson<T>()
line in SendRequestAsync
and change the method signature to return Task<HttpResponseMessage>
:
using System.Net.Http;
public static async Task<HttpResponseMessage> SendRequestAsync(string baseUrl, Dictionary<string, string> body)
{
using (var flurl_client = new FlurlClient(baseurl))
{
try
{
var response = await flurl_client
.Request()
.PostUrlEncodedAsync(body); // this returns Task<HttpResponseMessage>
return response;
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
return null;
}
}
Then your test can do this:
var resp = await Helper.SendRequestAsync(...);
Assert.AreEqual(HttpStatusCode.OK, resp.StatusCode);
Anything that needs the deserialized response body can do this:
var token = await Helper.SendRequestAsync(...).ReceiveJson<AccessToken>();