Selenium


 Automate web application using selenium
1.Add unit test project in Visual Studio 
2.Add NuGet packages 
Right click on the project name (Ex: MyTestProject) under Solution Explorer and click on Manage NuGet Package 
 
Figure 1 

Type the Selenium under Browse tab and search, then select Selenium.WebDriver and install 
 
Figure 2 
Then Click Yes to All 
 
Figure 3 
Same way add following NuGet package 
Selenium.Chrome.WebDriver 
Selenium.Support 

3.Let’s automate google search 
Write the test method as follow, 

   [TestMethod] 
Line 1   public void TestMethod1() 
Line 2   { 
Line 3      var Driver = new ChromeDriver(); 
Line 4      Driver.Navigate().GoToUrl("https://www.google.com/"); 
Line 5      Driver.Manage().Window.Maximize();    
Line 6      Driver.FindElementByName("q").SendKeys("Hello"); 
Line   } 


Line 3 
First it will initialize the Chrome web driver which can be used to load the web URL. 
Line 4  
Load the google.com url 
Line 5 
Maximums the web browser 
Line 6  
Type the test in search text box 

In C# test project we can have TestInitialize() attribute to initialize the test case and TestCleanup() to close the driver. See example below 

 
Figure 4 

4.Common method use in selenium (Ref 1) 

Driver.FindElementById("Id"); 
Driver.FindElementByClassName("ClassName"); 
Driver.FindElementByCssSelector("CssSelector"); 
Driver.FindElementByLinkText("LinkTest"); 
Driver.FindElementByName("Name"); 
Driver.FindElementByPartialLinkText("PartialLinkTest"); 
Driver.FindElementByTagName("Name"); 
Driver.FindElementByXPath("Xpath"); 

  
Ex: 
 
Figure 5 
Above html code we can see the button attribut as below 
ID = submit 
Name = submit 
Class = btn 
So, our find element can as below 
Driver.FindElementById("submit"); 
Driver.FindElementByClassName("btn"); 
Driver.FindElementByName("submit"); 

5.How to find XPath in chrome. 
Right click on the element (Google search box) that you want to find the element. 
 
Then right click on the element code and go to Copy >> Copy XPath 
 
Then your Xpath will as below, 
//*[@id="q"] 

Driver.FindElementByXPath("//*[@id=q]"); 



Reference 

No comments:

Post a Comment