Chuan Chuan Law

DevOps | Software Automation | Continuous Integration

Tag: C#

Testing API in C# – WebClient – How To Post A Request

Testing API in C# – WebClient – How To Get A Request

Below is how to Get a request using WebClient instead of HTTPClient

 

Testing API In C# – HttpClient – How To Get A Request

Back in days when I was working with Ruby on a MacBook Pro, I got Curl. However, now as I am using a PC in a .NET shop, I need to use compatible technology to test API – HttpClient is my solution.

Install the Web API Client Libraries via Package Manager Console

Install-Package Microsoft.AspNet.WebApi.Client

Sample code as below:


  • [Fact] is merely an XUnit notation indicating that this is a unit test
  • using creates an HttpClient instance which is only active within the scope
  • await suspends operation until the execution is completed
  • Method is declared as async as HttpClient methods perform I/O
  • ReadAsStringAsync() will read the output as string
  • JsonConvert.Deserializeobject<> will parse the string into the object model LanguageDictionary
  • You can use many methods from the HttpResponseMessage to verify the response from the API

 

Uploading Files in Windows Using Selenium C#

I have encountered a situation where I need to click on a button in order to upload a file.

I test this using Selenium C# by:

1. Entering the file path into the box

driver.FindElement(By.Id(“uploadFile”)).SendKeys(“C/testFile.txt”);

2. Calling the Javascript function to simulate what happens when “Upload” button is clicked

IJavaScriptExecutor js = driver as IJavaScriptExecutor;

string script = “__doPostBack(‘uploadFileButton’,”)”;

js.ExecuteScript(script);

SpecFlow + C# – Read a row from database to check the value

 

 [Then(@”we verify that the (.*) row contains (.*) of (.*)”)]
        public void ThenWeVerifyThatTheFirstRowContainsLInstIDOf410(String row, String field, String value)
        {
            SqlConnection ThisConnection = new SqlConnection(@”Server=1.1.0.26;Database=pp5_410_LK;Trusted_Connection=True”);
            ThisConnection.Open();
            SqlCommand thisCommand = ThisConnection.CreateCommand();
            if (String.Compare(row,”first”)==0)
            {
                thisCommand.CommandText = “select * from CostCentre where sCostCentreNo in (select MAX(sCostCentreNo) from CostCentre where lInstID=410) and lInstID=410”;
            }
            if (String.Compare(row, “last”) == 0)
            {
                thisCommand.CommandText = “select * from CostCentre where sCostCentreNo in (select MIN(sCostCentreNo) from CostCentre where lInstID=410) and lInstID=410”;
            }
            SqlDataReader thisReader = thisCommand.ExecuteReader();
            try
            {
                while (thisReader.Read())
                {
                    Console.WriteLine(thisReader[field].ToString());
                    Assert.AreEqual(value, thisReader[field].ToString());
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            thisReader.Close();
            ThisConnection.Close();
        }

SpecFlow + C# – Execute a script and how to make step definitions reusable

//This is how we can make the step definitions reusable

[When(@”I run the (.*)”)]
            public void WhenIRunTheGenericImporter(String importer)
            {
               if (String.Compare(importer,”GenericImporter”)==0)
               {
                   StartInfo.FileName = @”C:\TrunkbinDebugWinExecutablesGenericImporter.exe”;
               }
               if (String.Compare(importer,”PageUpImporter”)==0)
               {
                   StartInfo.FileName = @”C:\TrunkbinDebugWinExecutablesPageUpImporter.exe”;
//Passing in argument to the command
                   StartInfo.Arguments = @”lk 410″;
               }

               ProcessStartInfo StartInfo = new ProcessStartInfo();

               Process Process = new Process();
               StartInfo.RedirectStandardOutput = true;
               StartInfo.RedirectStandardError = true;
               StartInfo.UseShellExecute = false;
               StartInfo.CreateNoWindow = true;
               Process.StartInfo = StartInfo;
               Process.Start();
            }

SpecFlow + C# – Connect to a SQL database

 

 [Given(@”we clean the database”)]
        public void GivenWeCleanTheDatabase()
        {
           SqlConnection ThisConnection = new SqlConnection(@”Server=1.10.26;Database=410_LK;Trusted_Connection=True”);
            ThisConnection.Open();
            SqlCommand thisCommand = ThisConnection.CreateCommand();
            thisCommand.CommandText = “delete from costcentre where linstid = 410”;
            SqlDataReader thisReader = thisCommand.ExecuteReader();
            thisReader.Close();
            ThisConnection.Close();
        }

Selenium – C#

This post contains the key commands for Selenium in C#

  • Initialise a new driver

IWebDriver driver = new FirefoxDriver();



  • Navigation

driver.Navigate().GoToUrl(https://google.com/);



  • Clear a field

driver.FindElement(By.XPath(“//input[@name=’sName’]”)).Clear();



  • Entering a text

driver.FindElement(By.XPath(“//input[@name=’sName’]”).SendKeys(“Testing 123”);



  • Click on an element

driver.FindElement(By.XPath(“//input[@name=’sName’]”).Click();




  • Wait until an element is found

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));

IWebElement employeeSearch = wait.Until((d) =>

{ return

d.FindElement(

By.XPath(

“/html/body[@id=’ctl00__objBodyTag’]/form[@id=’aspnetForm’]/table/tbody/tr[2]/td/table/tbody/tr/td[@id=’menuCell’]/div[@id=’menu’]/div/ul/li[@id=’user’]/ul/li[2]/a”));

});

employeeSearch.Click();




  • Switch to other windows
ReadOnlyCollection handles = driver.WindowHandles;
driver.SwitchTo().Window(handles.ElementAt(0));
 
 
  • Select an element
new SelectElement(driver.FindElement(By.XPath(“//select[@id=’test’]”))).SelectByIndex(2);
 
 
  • Sleep
System.Threading.Thread.Sleep(2000);

  • Quit
driver.Quit();

© 2019 Chuan Chuan Law

Theme by Anders NorenUp ↑