简体   繁体   中英

C# HttpClient - GET - Parse response and assert

I am using HttpClient to make a GET call and i want to parse the Json response and assert the key value pairs

This is my code

public partial class EntityClass
{
    [JsonProperty("StatusCode")]
    public string StatusCode { get; set; }

    // more code
}

using (HttpClientHandler handler = new HttpClientHandler())
            {
                handler.Credentials = new NetworkCredential(@"Domain\user", "password");
                using (HttpClient client = new HttpClient(handler))
                {
                    client.BaseAddress = new Uri("https://baseURL");
                    client.DefaultRequestHeaders.Accept.Clear();
                    HttpResponseMessage response = await client.GetAsync("api/apiendpoint")
                    response.EnsureSuccessStatusCode();

                    string responsebody = response.Content.ReadAsStringAsync().Result;
                    var data = JsonConvert.DeserializeObject<EntityClass>(responsebody);
                    
                }
            }

I can assert the response like this

Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);

However I want to assert each Key Value pair in the Json response. I cant get it to work with the above code How can I access the key value pair and assert?

For example if the Json Response is:

{
StatusCode:200,
Key1: Value1,
Key2: Value2
}

I want to be able to assert like

Assert.AreEqual(200,data.StatusCode);
Assert.AreEqual(Value1, data.Key1);
Assert.AreEqual(Value2, data.Key2);

However in my code response.StatusCode returns OK and not 200

As the commenters noted, the status code is not part of the body, but you appear to be handling that part correctly.

To get to the key/value pairs as you call them, you can parse the string into an intermediate representation, and then iterate over the properties of that representation. This avoids having to have the native .NET type that would normally be populated, which may be preferable to avoid having the automation test depend on a specific type.

So, it depends on which serializer you can or have to use. Since I see JsonConvert in your code you're using Newtonsoft's code. In that case use JObject.Parse() :

using Newtonsoft.Json.Linq;
...
var expectedValues = new Dictionary<string, object>();
var responsebody = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
var root = JObject.Parse(responsebody);

foreach (var property in root.Properties)
{
    // not tested, but you get the idea...
    var expectedValue = expectedValues[property.Name];
    if (expectedValue == null)
        // null has to be checked via token type
        Assert.IsTrue(property.Value.Type == JTokenType.Null);
    else
        // check they are same type AND value
        Assert.AreEqual(property.Value.ToObject(expectedValue.GetType()), expectedValue);
}

The trick here is that you need to create a dictionary that maps expected keys to expected values, and then check these values against what's in the intermediate representation. This can be used to prove that no unexpected key is in the output (because there would be no dictionary entry) and to prove that for the keys returned, their values are expected.

To also prove there are no missing keys, you can check the keys of the dictionary against the names of the returned properties.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM