visual studio para org openqa guru99 español ejemplos chrome c# selenium firefox webdriver automated-tests
here

studio - ¿Cómo uso Selenium en C#?



selenium para c# (8)

  1. Instalar el gestor de paquetes Nuget
    Enlace de descarga: https://visualstudiogallery.msdn.microsoft.com/27077b70-9dad-4c64-adcf-c7cf6bc9970c
  2. Crear una aplicación de consola c # visual
  3. Haga clic derecho en el proyecto -> Administrar paquetes de Nuget.
    Busque "Selenium" e instale el paquete Selenium.Support

Listo ahora estás listo para escribir tu código :)

Para codigo con descarga IE es decir driver
Enlace: http://selenium-release.storage.googleapis.com/index.html
Abre 2.45 porque es la última versión. Descarga IEDriverServer_x64_2.45.0.zip o IEDriverServer_Win32_2.45.0.zip
Extraiga y simplemente pegue el archivo .exe en cualquier ubicación, por ejemplo, C: /
Recuerde el camino para su uso posterior.

OverAll ref link: http://www.joecolantonio.com/2012/07/31/getting-started-using-selenium-2-0-webdriver-for-ie-in-visual-studio-c/

MI código de muestra:

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"); } } } }

Selenium

Descargué los controladores de cliente C # y el IDE. Logré grabar algunas pruebas y las ejecuté con éxito desde el IDE. Pero ahora quiero hacer eso usando C #. Agregué todos los DLL relevantes (Firefox) al proyecto, pero no tengo la clase Selenium . Algún hola mundo estaría bien.


Configurar ide para selenio junto con c # es usar Visual Studio Express. Y usted puede nUnit como el marco de prueba. A continuación los enlaces le proporcionan más detalles. Parece que has configurado lo que se explica en el primer enlace. Así que revise el segundo enlace para obtener más detalles sobre cómo crear un script básico

Cómo configurar los controladores de cliente C #, nUnit y selenium en VSExpress para pruebas automatizadas

Creación de un caso de prueba del controlador web de Selenium básico utilizando Nunit y C #

Código de muestra del blog de arriba.

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(); ) } }


De la seleniumhq.org/docs/… :

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(); } }


Sé que esta es una pregunta antigua, pero pensé que pondría esta información para otros.

Una de las cosas que me costó encontrar fue cómo usar PageFactory en C #. Especialmente para multiples IWebElements. Si desea utilizar PageFactory, aquí hay algunos ejemplos. Fuente: PageFactory.cs

Para declarar un elemento web html use esto dentro del archivo de clase.

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;

No olvide crear una instancia de los elementos de la página dentro del constructor.

public MyClass(){ PageFactory.InitElements(driver, this); }

Ahora puedes acceder a ese elemento en cualquiera de tus archivos o métodos. También podemos tomar caminos relativos de esos elementos si alguna vez lo deseamos. Prefiero pagefactory porque:

  • Nunca necesito llamar directamente al controlador usando driver.FindElement (By.Id ("id"))
  • Los objetos son perezosos inicializados.

Lo utilizo para escribir mis propios métodos de esperar por elementos, los envoltorios WebElements para acceder solo a lo que necesito exponer a los scripts de prueba y ayuda a mantener todo limpio.

Esto hace la vida mucho más fácil si tiene elementos web dinámicos (autogerados) como listas de datos. Simplemente crea un contenedor que llevará los elementos IWeb y agregue métodos para encontrar el elemento que está buscando.


Use el siguiente código una vez que haya agregado todas las bibliotecas de C # requeridas al proyecto en las referencias.

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(); } } }


DO#

  1. En primer lugar, descargue Selenium IDE para Firefox desde Selenium IDE . Use y juegue con él, luego pruebe un escenario, registre los pasos y luego expórtelo en C # o proyecto de Java según sus requisitos.

El archivo de código contiene el código algo así como:

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)); // Waiter 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; } } } }

  1. Necesitas obtener el driver chrome desde here
  2. Necesita obtener paquetes de nugget y las dll necesarias para el sitio web de Selenium Nuget
  3. Debe comprender los conceptos básicos de Selenium del sitio web de selenium docs

Eso es todo ...


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(); } }


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);