Writing your first Selenium C# test

In this post, I will show how to write a simple test case in selenium using C#. The site that I will use is available for free https://demowf.aspnetawesome.com/.


To allow selenium to interact with the browser and its elements we need to provide selenium a way to identify each element and its corresponding attributes. For example, if we want to access and write text in the “Autocomplete” window, we first need to provide selenium a unique identifier so he can recognize and access it.


To do it, we can inspect the element by right-clicking on it and select the inspect option. As you can see, the element as a unique ID (Which is not always the case) that we will use in our code.

Code:


using NUnit.Framework;

using OpenQA.Selenium;

using OpenQA.Selenium.Chrome;

using OpenQA.Selenium.Firefox;

using System;


namespace SeleniumCSharpCourse2021

{

public class Tests

{

public IWebDriver Driver;

[SetUp]

public void Setup()

{

Driver = new FirefoxDriver();

}


[Test]

public void Test1()

{

Driver.Navigate().GoToUrl("https://demowf.aspnetawesome.com/");//To open the site

Driver.FindElement(By.Id("ContentPlaceHolder1_Meal")).SendKeys("Tomato");//To locate and send text

//Assert.Pass();

//Driver.Quit();

}

}

}


The ID of elements is not always available, so therefore we have other options to locate elements. In this example we will locate an element by its XPath:

Code:


using NUnit.Framework;

using OpenQA.Selenium;

using OpenQA.Selenium.Chrome;

using OpenQA.Selenium.Firefox;

using System;


namespace SeleniumCSharpCourse2021

{

public class Tests

{

public IWebDriver Driver;

[SetUp]

public void Setup()

{

Driver = new FirefoxDriver();

}


[Test]

public void Test1()

{

Driver.Navigate().GoToUrl("https://demowf.aspnetawesome.com/");//To open the site

Driver.FindElement(By.XPath("/html/body/form/div[3]/div/div[3]/div/div[1]/div[4]/div[2]/div[2]/div/ul/li[1]/label/div[1]/div/div")).Click();

}

}

}



41 views0 comments