Selenium.
I downloaded the C# client drivers and the IDE. I managed to record some tests and successfully ran them from the IDE. But now I want to do that using C#. I added all relevant DLL files (Firefox) to the project, but I don't have the Selenium class. Some Hello, World! would be nice.
From the Selenium Documentation:
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium;
class GoogleSuggest
{
static void Main(string[] args)
{
IWebDriver driver = new FirefoxDriver();
//Notice navigation is slightly different than the Java version
//This is because 'get' is a keyword in C#
driver.Navigate().GoToUrl("http://www.google.com/");
IWebElement query = driver.FindElement(By.Name("q"));
query.SendKeys("Cheese");
System.Console.WriteLine("Page title is: " + driver.Title);
driver.Quit();
}
}
Install the NuGet packet manager
Download link: https://visualstudiogallery.msdn.microsoft.com/27077b70-9dad-4c64-adcf-c7cf6bc9970c
Create a C# console application
Right-click on the project → Manage NuGet Packages.
Search for "Selenium" and install package Selenium.Support.
You are done now, and you are ready to write your code :)
For code with Internet Explorer, download the Internet Explorer driver.
Link: http://selenium-release.storage.googleapis.com/index.html
Open 2.45 as its the latest release
Download IEDriverServer_x64_2.45.0.zip or IEDriverServer_Win32_2.45.0.zip
Extract and simply paste the .exe file at any location, for example C:\
Remember the path for further use.
Overall reference link: Selenium 2.0 WebDriver with Visual Studio, C#, & IE – Getting Started
My sample code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.IE;
namespace Selenium_HelloWorld
{
class Program
{
static void Main(string[] args)
{
IWebDriver driver = new InternetExplorerDriver("C:\\");
driver.Navigate().GoToUrl("http://108.178.174.137");
driver.Manage().Window.Maximize();
driver.FindElement(By.Id("inputName")).SendKeys("apatra");
driver.FindElement(By.Id("inputPassword")).SendKeys("asd");
driver.FindElement(By.Name("DoLogin")).Click();
string output = driver.FindElement( By.XPath(".//*[#id='tab-general']/div/div[2]/div[1]/div[2]/div/strong")).Text;
if (output != null )
{
Console.WriteLine("Test Passed :) ");
}
else
{
Console.WriteLine("Test Failed");
}
}
}
}
To set up the IDE for Selenium in conjunction with C# is to use Visual Studio Express. And you can use NUnit as the testing framework. The below links provide you more details. It seems you have set up what is explained in the first link. So check the second link for more details on how to create a basic script.
How to setup C#, NUnit and Selenium client drivers on Visual Studio Express for Automated tests
Creating a basic Selenium web driver test case using NUnit and C#
Sample code from the above blog post:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
// Step a
using OpenQA.Selenium;
using OpenQA.Selenium.Support;
using OpenQA.Selenium.Firefox;
using NUnit.Framework;
namespace NUnitSelenium
{
[TestFixture]
public class UnitTest1
{
[SetUp]
public void SetupTest()
{
}
[Test]
public void Test_OpeningHomePage()
{
// Step b - Initiating webdriver
IWebDriver driver = new FirefoxDriver();
// Step c: Making driver to navigate
driver.Navigate().GoToUrl("http://docs.seleniumhq.org/");
// Step d
IWebElement myLink = driver.FindElement(By.LinkText("Download"));
myLink.Click();
// Step e
driver.Quit();
)
}
}
One of the things that I had a hard time finding was how to use PageFactory in C#. Especially for multiple IWebElements. If you wish to use PageFactory, here are a few examples. Source: PageFactory.cs
To declare an HTML WebElement, use this inside the class file.
private const string _ID ="CommonIdinHTML";
[FindsBy(How = How.Id, Using = _ID)]
private IList<IWebElement> _MultipleResultsByID;
private const string _ID2 ="IdOfElement";
[FindsBy(How = How.Id, Using = _ID2)]
private IWebElement _ResultById;
Don't forget to instantiate the page object elements inside the constructor.
public MyClass(){
PageFactory.InitElements(driver, this);
}
Now you can access that element in any of your files or methods. Also, we can take relative paths from those elements if we ever wish to. I prefer pagefactory because:
I don't ever need to call the driver directly using driver.FindElement(By.Id("id"))
The objects are lazy initialized
I use this to write my own wait-for-elements methods, WebElements wrappers to access only what I need to expose to the test scripts, and helps keeps things clean.
This makes life a lot easier if you have dynamic (autogerated) webelements like lists of data. You simply create a wrapper that will take the IWebElements and add methods to find the element you are looking for.
FirefoxDriverService service = FirefoxDriverService.CreateDefaultService(#"D:\DownloadeSampleCode\WordpressAutomation\WordpressAutomation\Selenium", "geckodriver.exe");
service.Port = 64444;
service.FirefoxBinaryPath = #"C:\Program Files (x86)\Mozilla Firefox\firefox.exe";
Instance = new FirefoxDriver(service);
C#
First of all, download Selenium IDE for Firefox from the Selenium IDE.
Use and play around with it, test a scenario, record the steps, and then export it as a C# or Java project as per your requirement.
The code file contains code something like:
using System;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
// Add this name space to access WebDriverWait
using OpenQA.Selenium.Support.UI;
namespace MyTest
{
[TestClass]
public class MyTest
{
public static IWebDriver Driver = null;
// Use TestInitialize to run code before running each test
[TestInitialize()]
public void MyTestInitialize()
{
try
{
string path = Path.GetFullPath(""); // Copy the Chrome driver to the debug
// folder in the bin or set path accordingly
Driver = new ChromeDriver(path);
}
catch (Exception ex)
{
string error = ex.Message;
}
}
// Use TestCleanup to run code after each test has run
[TestCleanup()]
public void MyCleanup()
{
Driver.Quit();
}
[TestMethod]
public void MyTestMethod()
{
try
{
string url = "http://www.google.com";
Driver.Navigate().GoToUrl(url);
IWait<IWebDriver> wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(30.00)); // Wait in Selenium
wait.Until(ExpectedConditions.PresenceOfAllElementsLocatedBy(By.XPath(#"//*[#id='lst - ib']")));
var txtBox = Driver.FindElement(By.XPath(#"//*[#id='lst - ib']"));
txtBox.SendKeys("Google Office");
var btnSearch = Driver.FindElement(By.XPath("//*[#id='tsf']/div[2]/div[3]/center/input[1]"));
btnSearch.Click();
System.Threading.Thread.Sleep(5000);
}
catch (Exception ex)
{
string error = ex.Message;
}
}
}
}
You need to get the Chrome driver from here.
You need to get NuGet packages and necessary DLL files for the Selenium NuGet website.
You need to understand the basics of Selenium from the Selenium documentation website.
That's all...
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Interactions;
using OpenQA.Selenium.Support.UI;
using SeleniumAutomationFramework.CommonMethods;
using System.Text;
[TestClass]
public class SampleInCSharp
{
public static IWebDriver driver = Browser.CreateWebDriver(BrowserType.chrome);
[TestMethod]
public void SampleMethodCSharp()
{
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5));
driver.Url = "http://www.store.demoqa.com";
driver.Manage().Window.Maximize();
driver.FindElement(By.XPath(".//*[#id='account']/a")).Click();
driver.FindElement(By.Id("log")).SendKeys("kalyan");
driver.FindElement(By.Id("pwd")).SendKeys("kalyan");
driver.FindElement(By.Id("login")).Click();
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
IWebElement myDynamicElement = wait.Until<IWebElement>(d => d.FindElement(By.LinkText("Log out")));
Actions builder = new Actions(driver);
builder.MoveToElement(driver.FindElement(By.XPath(".//*[#id='menu-item-33']/a"))).Build().Perform();
driver.FindElement(By.XPath(".//*[#id='menu-item-37']/a")).Click();
driver.FindElement(By.ClassName("wpsc_buy_button")).Click();
driver.FindElement(By.XPath(".//*[#id='fancy_notification_content']/a[1]")).Click();
driver.FindElement(By.Name("quantity")).Clear();
driver.FindElement(By.Name("quantity")).SendKeys("10");
driver.FindElement(By.XPath("//*[#id='checkout_page_container']/div[1]/a/span")).Click();
driver.FindElement(By.ClassName("account_icon")).Click();
driver.FindElement(By.LinkText("Log out")).Click();
driver.Close();
}
}
You will need to install Microsoft Visual Studio community Edition
Create a new project as Test Project of C#
Add Selenium references from the NuGet Package Manager. Then you will be all set.
Create a new class and use [Test Class] and [Test Method] annotations to run your script
You can refer to Run Selenium C# | Setup Selenium and C# | Configure Selenium C# for more details.
Use the below code once you've added all the required C# libraries to the project in the references.
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
namespace SeleniumWithCsharp
{
class Test
{
public IWebDriver driver;
public void openGoogle()
{
// creating Browser Instance
driver = new FirefoxDriver();
//Maximizing the Browser
driver.Manage().Window.Maximize();
// Opening the URL
driver.Navigate().GoToUrl("http://google.com");
driver.FindElement(By.Id("lst-ib")).SendKeys("Hello World");
driver.FindElement(By.Name("btnG")).Click();
}
static void Main()
{
Test test = new Test();
test.openGoogle();
}
}
}
Related
Environment:
Vs2019, C#
NuGet Package: Selenium v3.141.0 by Selenium Committee.
Chrome Driver from Selenium website - v92.0
IWebDriver Driver = new ChromeDriver("FolderPath"); //time out error here.
Driver.url = "www.google.com"
with no other code, I can't get pass declaring Chrome Driver. I get a time out error with local host.
I tried:
setting a different port.
adding "no-sandbox" to arguments.
I would try utilizing the ChromeDriver NuGet package instead of pointing to a local file location
https://www.nuget.org/packages/Selenium.WebDriver.ChromeDriver/
Here is a simple example for you to reference
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
namespace ExampleDemo
{
[TestFixture]
public class Chrome_test
{
private IWebDriver driver;
[Test(Description="Go To Google")]
public void GoToGoogle() {
homeURL = https://www.google.com/;
driver.Navigate().GoToUrl(homeURL);
}
[TearDown]
public void TearDownTest()
{
driver.Close();
}
[SetUp]
public void SetupTest()
{
driver = new ChromeDriver();
}
}
}
I need to add a chrome option:
ChromeOptions options = new ChromeOptions()
options.add("--remote-debugging-port=9222 ") // change port if necessary
using OpenQA.Selenium;
using OpenQA.Selenium.Appium;
using OpenQA.Selenium.Remote;
using System;
using System.Threading;
using Xunit;
namespace XUnitTestProject2
{
public class UnitTest1
{
[Fact]
public void Test1()
{
Thread.Sleep(3000);
var driver = InitiliseDriver();
//Login Page
driver.FindElement(By.Id("username")).SendKeys("TestUser");
driver.FindElement(MobileBy.Id("password")).SendKeys("newpassword");
driver.FindElement(MobileBy.Id("91268f5d-d21e-4ef5-9886-c1d19f2799a7")).Click();
}
private RemoteWebDriver InitiliseDriver()
{
//Set the capabilities
DesiredCapabilities cap = new DesiredCapabilities();
cap.SetCapability("platformName", "Android");
cap.SetCapability("platformVersion", "9.0");
cap.SetCapability("app", "C:\\Users\\jamesa\\Downloads\\app-debug.apk");
//cap.SetCapability("automationName", "uiautomator2");
return new RemoteWebDriver(new Uri("http://127.0.0.1:4723/wd/hub"), cap);
}
}
}
My nuget packages are Appium.WebDriver(4.1.1); Microsoft.Net.Test.Sdk(16.0.1); Selenium.Support(3.141.0); Selenium.WebDriver(3.141.0); Xunit(2.4.0); Xunit.runner.visualstudios(2.4.0); MSTest.TestAdapter(2.1.2); MSTest.TestFramework(2.1.2)
My Desired Capabilities are platformName- Text- Android; platformVersion- Text - 9.0; app - Text - \\\
This is the session details I am getting I do have selector ID but the server is not picking it
Note: - I am able to launch the application successfully but the server is unable to pick the element. - The application is built in an Ionic way (Ionic 5)
You need to set your driver context to WEBVIEW, ionic builds apps with webview (not native), also you might want to build your app in debug mode. Here is more details on testing hybrid applications with appium.
In your case you would need to add something like this, before executing the tests
driver.context("WEBVIEW");
I'm implemented Nunit selenium C# testing in visual studio (Console Application n Class Library). My project in visual studio is console application. I started the selenium grid using
java -Dwebdriver.gecko.driver="..\jar\geckodriver.exe" -Dwebdriver.chrome.driver="..\jar\chromedriver.exe" -Dwebdriver.ie.driver="..\jar\IEDriverServer.exe" -jar ..\jar\selenium-server-standalone-3.14.0.jar -role hub -port 4444
Code:
using Automation_Framework.Manager;
using NUnit.Framework;
using OpenQA.Selenium;
using System;
using System.Collections.Generic;
using System.Text;
namespace Automation_Framework.TestManager
{
[TestFixture]
class ChromeTestManager
{
private WebDriverManager webDriverManager;
private IWebDriver driver;
public ChromeTestManager()
{
webDriverManager = new WebDriverManager();
}
[SetUp]
public void setup()
{
webDriverManager.createDriver("chrome");
driver = webDriverManager.getDriver();
}
[Test]
public void test()
{
driver.Url = "http://www.google.com.my";
driver.Navigate();
}
[TearDown]
public void shutdown()
{
driver.Close();
}
}
}
I had tried execute using Test Explorer but it does not open any browser. I"m following this tutorial.
Questions:
How to run the project with browser open and see all actions?
How to run using Nunit-console-runner.
Please help me. Thanks.
I assume that:
1. You have tried your code locally and your test is opening the browser when you run it on your machine without the grid.
2. Your nodes are set up and registered with the hub.
You need to:
1. Use RemoteWebDriver:
var uri = 'uri_to_your_grid_hub';
var capabilities = new ChromeOptions().ToCapabilities();
var commandTimeout = TimeSpan.FromMinutes(5);
var driver = new RemoteWebDriver(new Uri(uri),capabilities,commandTimeout)
Add the attribute to a class: [Parallelizable(ParallelScope.Self)] in order to run your tests in parallel with other test classes.
In order to verify whether the hub is running, open the browser and navigate to http://localhost:4444 on the hub machine.
Sources:
How can I run NUnit(Selenium Grid) tests in parallel?
Selenium Grid in C#
Useful C# WebDriver examples
Selenium Grid set up
I haven't used grid in .Net but here my answer:
your command is just register a hub, which needs to keep running (open a browser and test it is working)
you need to register your nodes under that hub (different ports) (open a browser and test it is working)
in your code, you should use "RemoteWebDriver" to connect to the hub.
something along these lines (it is in java but I hope it gives you a starting point)
public class Gmail
{
public WebDriver driver=null;
#Parameters("browser") //testng.xml
#Test()
public void GmailTest(String browser)
{
System.out.println("Gmail " + browser);
// RemoteWebdriver
DesiredCapabilities cap = null;
if(browser.equals("firefox")){
cap = DesiredCapabilities.firefox();
cap.setBrowserName("firefox");
cap.setPlatform(Platform.ANY);
}else if (browser.equals("iexplore")){
cap = DesiredCapabilities.internetExplorer();
cap.setBrowserName("iexplore");
cap.setPlatform(Platform.WINDOWS);
}
driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"),cap);
driver.get("http://gmail.com");
driver.findElement(By.id("Email")).sendKeys("abcd");
driver.quit();
}
I hope this helps.good luck
I am getting an exception System.ComponentModel.Win32Exception : The system cannot find the file specified when i employ Sikuli in C# using selenium.
I have referred to other posts in Stack but i have not not got a solution for that.
I am also running VS 2017 in administrator mode
I have latest copy of Rest-Api Jar in /Debug folder.
Below is my code
using System;
using System.Threading;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Interactions;
using OpenQA.Selenium.Support.UI;
using Sikuli4Net.sikuli_REST;
using Sikuli4Net.sikuli_UTIL;
using SikuliModule;
namespace DownloadFile
{
public class Download
{
private IWebDriver driver;
private APILauncher launcher;
[SetUp]
public void setup()
{
driver = new FirefoxDriver();
launcher = new APILauncher(true);
driver.Navigate().GoToUrl("https://java.com/en/download/");
driver.Manage().Window.Maximize();
}
[Test]
public void TestMethod1()
{
new WebDriverWait(driver, TimeSpan.FromSeconds(60)).Until(ExpectedConditions.ElementExists((By.XPath("//span[contains(text(),'Free Java Download')]")))).Click();
new WebDriverWait(driver, TimeSpan.FromSeconds(60)).Until(ExpectedConditions.ElementExists((By.XPath("//span[contains(text(),'Agree and Start Free Download')]")))).Click();
launcher.Start();
Screen screen = new Screen();
Pattern Click_Save = new Pattern("C:/Selenium Files/Save.jpg");
screen.Wait(Click_Save, 500);
screen.Click(Click_Save);
launcher.Stop();
}
}
}
Update your path of .jpg file in below line of code:
Pattern Click_Save = new Pattern("C:\\Selenium Files\\Save.jpg");
Rest of the code seems fine.
I'm working on trying to PNunit working for some Sauce Labs tests. But when I try launching it using the PNUnit Launcher.exe, I get the following error message:
"The test PNUnit_Test.SauceTest.TestCase couldn't be found in the assembly PNUnit.Test.dll"
Here's my sample test code:
using NUnit.Framework;
using PNUnit.Framework;
using System;
using System.Web;
using System.Text;
using System.Net;
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Support.UI;
namespace PNUnit_Test
{
[TestFixture()]
public class SauceTest
{
private IWebDriver driver;
private string[] testParams;
[SetUp]
public void Init()
{
testParams = PNUnitServices.Get().GetTestParams();
String params1 = String.Join(",", testParams);
Console.WriteLine(params1);
String browser = testParams[0];
String version = testParams[1];
String os = testParams[2];
String os_version = testParams[3];
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.SetCapability("browserName", browser);
capabilities.SetCapability(CapabilityType.Version, version);
capabilities.SetCapability("os", os);
capabilities.SetCapability("os_version", os_version);
capabilities.SetCapability("username", Constants.SAUCE_LABS_ACCOUNT_NAME);
capabilities.SetCapability("accessKey", Constants.SAUCE_LABS_ACCOUNT_KEY);
Console.WriteLine("Capabilities" + capabilities.ToString());
driver = new RemoteWebDriver(new Uri("http://ondemand.saucelabs.com:80/wd/hub"), capabilities);
}
[Test]
public void TestCase()
{
driver.Navigate().GoToUrl("http://www.google.com");
StringAssert.Contains("Google", driver.Title);
IWebElement query = driver.FindElement(By.Name("q"));
query.SendKeys("Sauce Labs");
query.Submit();
}
[TearDown]
public void Cleanup()
{
driver.Quit();
}
}
}
And here's the conf file I using to set up my browsers I'll be using for my test:
<TestGroup>
<ParallelTests>
<ParallelTest>
<Name>Testing</Name>
<Tests>
<TestConf>
<Name>TestFF-40-Win8</Name>
<Assembly>PNUnit_Test.dll</Assembly>
<TestToRun>PNUnit_Test.SauceTest.TestCase</TestToRun>
<Machine>localhost:8081</Machine>
<TestParams>
<string>firefox</string> <!--browserName -->
<string>40.0</string> <!-- version -->
<string>Windows</string><!-- os -->
<string>8</string><!-- os_version -->
</TestParams>
</TestConf>
<TestConf>
<Name>TestFF-21-win7</Name>
<Assembly>PNUnit_Test.dll</Assembly>
<TestToRun>PNUnit_Test.SauceTest.TestCase</TestToRun>
<Machine>localhost:8081</Machine>
<TestParams>
<string>firefox</string> <!--browserName -->
<string>21.0</string> <!-- version -->
<string>Windows</string><!-- os -->
<string>7</string><!-- os_version -->
</TestParams>
</TestConf>
</Tests>
</ParallelTest>
</ParallelTests>
</TestGroup>
Not sure what I could be doing wrong and finding information about C# Selenium Testing using PNUnit is sparse, so any helpful hints will be appreciated. Thank you!
Figured it out. My C# project was built using the .NET 4 framework. PNUnit only works with .NET 3.5. On a personal note, glad that NUnit 3 will be able to run parallel projects built on Net40 and higher