Selenium WebDriver Test with C# and MsTest | Code Example

What is Selenium?

Selenium automates browsers. That’s it! What you do with that power is entirely up to you. Primarily, it is for automating web applications for testing purposes, but is certainly not limited to just that. Boring web-based administration tasks can (and should!) be automated as well.

Selenium has the support of some of the largest browser vendors who have taken (or are taking) steps to make Selenium a native part of their browser. It is also the core technology in countless other browser automation tools, APIs and frameworks.

Code Example | C#

Here is a sample code example of Selenium test with Java and MsTest.

using System;
using System.Linq;
using System.Threading;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;

namespace SeleniumCSharp
{
    [TestClass]
    public class SeleniumCSharp
    {
        private static IWebDriver Driver;
        private static String base_url = "https://softwaretestingblog.com";

        [AssemblyInitialize]
        public static void AssemblyInit(TestContext context)
        {
            Driver = new ChromeDriver();
            Driver.Manage().Window.Maximize();
            Driver.Navigate().GoToUrl(base_url);
        }

        [AssemblyCleanup]
        public static void AssemblyTearDown()
        {
            Driver.Close();
            Driver.Quit();
        }

        [TestMethod]
        public void SeleniumTestUsingCSharp()
        {
            Driver.FindElement(By.ClassName("ClassName")).SendKeys("Text");
            Driver.FindElement(By.TagName("Tag")).Click();
            Driver.FindElement(By.CssSelector("#CssSelector")).Click();
            Driver.FindElement(By.Id("Id")).Click();
            Driver.FindElement(By.Name("Name")).Click();
            Driver.FindElement(By.LinkText("LinkText")).Click();
            Driver.FindElement(By.XPath("//*[Xpath]")).Clear();

            SelectElement mydrpdwn = new SelectElement(Driver.FindElement(By.Id("Id")));
            mydrpdwn.SelectByText("Text");          
            mydrpdwn.SelectByValue("Value");
            mydrpdwn.SelectByIndex(1);

            Thread.Sleep(1000);

            Driver.SwitchTo().Window(Driver.WindowHandles.Last());
            Assert.AreEqual("URL", Driver.Url);
            Driver.Close();
            Driver.SwitchTo().Window(Driver.WindowHandles.First());

            Assert.IsTrue(Driver.FindElement(By.Name("Name")).Text.Contains("Text"));
            Assert.IsFalse(Driver.FindElement(By.Name("Name")).Text.Contains("Text"));

            IAlert Aleart = Driver.SwitchTo().Alert();
            Aleart.Accept();
        }
    }
}
Advertisements

Leave a Reply