Selenium WebDriver Java Framework Course Limited Time Offer for $20

Selenium WebDriver Java Framework Course Limited Time Offer for $20

 

Print

Test API With Selenium Web Driver in C#

Many web applications provide API for external clients to use in their internal applications. When testing APIs, QA engineers need to verify that what UI displayed should be equal to the API response for the same request input.  In this article, we use the Open Weather API as an example to test the web response for this url "api.openweathermap.org/data/2.5/weather?q=London,uk"   should be the same as the API response. The code is written in c#. We use C# NUnit framework and Selenium web driver in this code example.

 

Step 1: create a C# NUnit project and add Selenium web driver and NUnit library as references. see the screenshot below. Add a NUnit class item named "WeatherApiTests.cs" and add a class item named "ApiResponse.cs".

Step 2: write the code below in the "ApiResponse.cs" file.

 
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace ServiceApiTest
{
    class ApiResponse
    {
        private string ApiUrlString = "http://api.openweathermap.org/data/2.5/weather?q=";
        public string GetResponse(string city)
       {
           StringBuilder responseString = new StringBuilder();
            ApiUrlString = String.Format(ApiUrlString + "{0}", city);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(ApiUrlString);

            // Set some reasonable limits on resources used by this request
            request.MaximumAutomaticRedirections = 4;
            request.MaximumResponseHeadersLength = 4;
            // Set credentials to use for this request.
            request.Credentials = CredentialCache.DefaultCredentials;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse ();

            try
            {
             // Get the stream associated with the response.
            Stream receiveStream = response.GetResponseStream ();
            // Pipes the stream to a higher level stream reader with the required encoding format. 
                if (receiveStream != null)
                {
                    StreamReader readStream = new StreamReader (receiveStream, Encoding.UTF8);
                    string line = "";
                    while ((line = readStream.ReadLine()) != null)
                    {
                        responseString.Append(line);
                    }
                    Console.WriteLine ("Response stream received.");
                    Console.WriteLine(responseString);
                    response.Close ();
                    readStream.Close ();
                }
            }
            catch (Exception)
            {
                responseString.Append("Did not get response");

            }
            return responseString.ToString(); 
       }

    }
}

Step 3: write the code below in the "WeatherApiTests.cs" file.

 
using System;
using System.Threading;
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;

namespace ServiceApiTest
{
    [TestFixture]
    public class WeatherApiTests
    {
        private IWebDriver _webDriver;
        string BaseUrl="http://api.openweathermap.org/data/2.5/weather?q=";
        [SetUp]
        public void Setup()
        {
           _webDriver=new FirefoxDriver(); 
           _webDriver.Manage().Window.Maximize(); 
        }
        [Test]
        public void TestCity1()
        {
            const string cityString = "London,uk";
            ApiResponse apiResponse = new ApiResponse();
            string expectedResult = apiResponse.GetResponse(cityString);
            Thread.Sleep(5000);
            Console.WriteLine("-------------------- Web Page Displayed ------------------");
            _webDriver.Navigate().GoToUrl(BaseUrl+cityString);
          IWebElement responseElement= _webDriver.FindElement(By.TagName("pre"));
            string displayedResponse = responseElement.Text;
            Console.WriteLine(displayedResponse);
            Assert.IsTrue(expectedResult.Equals(displayedResponse));
        }
        [Test]
        public void TestCity2()
        {
            const string cityString = "Baltimore,usa";
            ApiResponse apiResponse = new ApiResponse();
            string expectedResult = apiResponse.GetResponse(cityString);
            Thread.Sleep(5000);
            Console.WriteLine("-------------------- Web Page Displayed ------------------");
              _webDriver.Navigate().GoToUrl(BaseUrl+cityString);
          IWebElement responseElement= _webDriver.FindElement(By.TagName("pre"));
          string displayedResponse = responseElement.Text;
          Console.WriteLine(displayedResponse);
          Assert.IsTrue(expectedResult.Equals(displayedResponse));
        }

        [TearDown]
        public void Teardown()
        {
            _webDriver.Close();
            _webDriver.Quit();
        }
    }
}

Step 4: run the tests as NUnit tests.

Step 5: see the result above. The result showed that two tests passed. In this example, we compared Weather Api Response displayed on the web UI with the Api response obtained from HTTP Web Request.