Bill Porter
Bill Porter

Reputation: 49

UnitTest Method for AJAX JSON Calls to an API

I am trying to write test cases for our AJAX calls to our API. Doing a simply web request and response. My question is with regard to the response. Is there a simpler way to pull out the response JSON values? Is the best way to do this sort of thing? I know we could us JQuery, but wanted to use Microsoft Testing framework.

    [TestMethod]
    public void TestMethod1()
    {
        string brand = "KEWL";
        string BRAND = "";

        var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://203.135.xx.138:4040/api/v1/subscriptions/signup.format");
        httpWebRequest.ContentType = "application/json";
        httpWebRequest.Method = "POST";

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string json = @"{" +
           " 'api_key': '91230D10-247C-11E1-83FF-9B9C4824019B'," +
           " 'phone': '12122639043', " +
           " 'dob': '11231954', " +
           "      'subscriptions': [ " +
           "                {" +
           "                 'Brand':'" + brand + "', " +
           "                'campaign':'BTLNDN', " +
           "                    'groups':[" +
           "                            {" +
           "                            'group': 'BTLALL'," +
           "                            'subscribed':true" +
           "                            } " +
           "                    ]," +
           "   'lang': 'en' " +
           "                }" +
           "                ] " +
           "   }";

            streamWriter.Write(json);
        }
        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var responseText = streamReader.ReadToEnd();
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            Dictionary<string, dynamic> dc = serializer.Deserialize<Dictionary<string, dynamic>>(responseText);
            var kev = dc;
            foreach (var key1 in dc.Keys)
            {
               var value3 = dc["ReturnData"]["subscriptions"];
                 BRAND = value3[0]["brand"];
             //   var groups = value3[0]["groups"];
            }


        }
        Assert.AreEqual(brand, BRAND);
    }

Upvotes: 0

Views: 669

Answers (1)

Wouter de Kort
Wouter de Kort

Reputation: 39898

The idea of unit testing ASP.NET MVC methods is that you can run the test without using any Http request or respond functionality.

Suppose you have the following method:

public class MyController : Controller
{
    public ActionResult MyAjax()
    {
        return Json(new { Test = "Test" });
    }
}

You can test it with this code:

[TestMethod]
public void MyTest()
{
    MyControllercontroller = new MyController();

    JsonResult json = controller.MyAjax() as JsonResult;

    Assert.IsNotNull(json);

    dynamic data = json.Data;

    Assert.AreEqual("Test", data.Test);
}

To use the dynamic keyword you have to make sure that your test project can see the internals of your web project (this is because anonymous types are declared internal). You can do this by adding: [assembly: InternalsVisibleTo("YourTestProject")] to the AssemblyInfo.cs file of your web project.

Upvotes: 3

Related Questions