Sunday 1 August 2021

RestSharp - Testing a RestFul API service endpoint

Following is the sample run with basic authentication option we have to test RestFul API service endpoint. 

////Json response with simple structure
        [Test]
        public void TestMethod2()
        {
            var client = new RestClient("https://XXXXXX/");

            var request = new RestRequest("api/v4/stb/addition/options/{CustomerId}", Method.GET);
            request.AddHeader("Authorization", "Basic R0xPUFRFU1RcRy5QQUxMQTpUbW9iaWxlNjY3OCE=");
            request.AddUrlSegment("CustomerId", "XLZ20261");

            var response = client.Execute(request);

            //Lib 1 - Dictionary based response
            //var deserialize = new JsonDeserializer();
            //var output = deserialize.Deserialize<Dictionary<string, string>>(response);
            //var result = output["author"];

            //Lib 2 - JSON based response
            JObject obs = JObject.Parse(response.Content);
            Assert.That((int)obs["StbsLeft"], Is.EqualTo(2), "Stbs left are not correct");
        }


////Json response with complex structure
        [Test]
        public void TestMethod3()
        {
            var client = new RestClient("https://XXXXXXX/");

            var request = new RestRequest("api/v4/stb/addition/options/{CustomerId}", Method.GET);
            request.AddHeader("Authorization", "Basic R0xPUFRFU1RcRy5QQUxMQTpUbW9iaWxlNjY3OCE=");
            request.AddHeader("Content-Type", "application/json");
            request.AddUrlSegment("CustomerId", "XLZ20261");

            var response = client.Execute(request);


            //Lib 2 - JSON based response
            JObject obs = JObject.Parse(response.Content);

// below Json response is a complex hierarchy structure, we have to take the path based on the structure
            Assert.That(obs["StbProducts"]["$values"][0]["name"].ToString(), Is.EqualTo("ABCD"), "Stb displayed is not correct");
        }

1 comment: