Click here to Skip to main content
15,894,825 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am doing REST API testing and the API call returns a JSON string. I am trying to check if the properties name is equal to a specific value. Currently this is what I have but it only looks a the Children token where the name I am asserting is not available, I want to find out how can I extract all the values.

What I have tried:

<pre> public static void VerifyJsonString(string response, string Key, string Value)
        {
             JArray jsonObject = JArray.Parse(response);
            Dictionary<string, object> myDictionary = new Dictionary<string, object>();
            foreach (JObject content in jsonObject.Children<JObject>())
            {
                foreach (JProperty prop in content.Properties())
                {
                    Assert.That(myDictionary.ContainsKey(Key), Is.EqualTo(Value));
                }
            }


//Here is my Get Call for refernce
      [Test]
       public void GetTagsList()
       {
restResponse = BaseServiceCall.HttpGet(baseUrl, TestUtil.BaseUrl(), null, token, client);
           var data = restResponse.Content;
           TestUtil.VerifyJsonString(data, "name", "TagTest");

       }
Posted
Updated 5-Jun-20 2:18am
Comments
Richard Deeming 5-Jun-20 5:00am    
That makes no sense. Your dictionary is empty, so ContainsKey will always return false. And a bool is never going to be equal to a string.

Show a sample of your JSON, and explain what you're actually trying to achieve.

1 solution

You need something like

C#
foreach (JProperty prop in content.Properties())
{
    if (prop.Name == Key)
    {
        Assert.That(prop.Value, Is.EqualTo(Value));
    }
}


or

C#
foreach (JProperty prop in content.Properties().Where(p => p.Name == Key))
{
    Assert.That(prop.Value, Is.EqualTo(Value));
}


As an aside, these aren't proper unit tests. You should write a test for the class that handles your api requests instead. That lets you ensure the logic is valid and doesn't require the project to be running somewhere, you should be able to run your unit tests anywhere, they shouldn't have dependencies on databases, servers etc. For example the build server will want to run your unit tests but how can it when it needs all sorts of config to find your api?

By testing it from the client level like you are doing you are testing two things...one is that your API does what you want, the other is that the HttpGet function is working. The problem here is that a) your test tests multiple things, it should only test one b) you didn't write the HttpGet, it's not your code so why are you testing it?
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900