Статьи

Microsoft Edge WebDriver: вот что вы должны знать

Как вы, возможно, знаете, одна из лучших доступных сред для создания тестов веб-автоматизации —  Selenium WebDriver . Microsoft публично  объявила,  что их новый веб-браузер Windows 10 — Edge будет поддерживать автоматизацию WebDriver ( Microsoft Edge WebDriver ). Конечно, я хотел попробовать это как можно быстрее, поэтому я подготовил все необходимое и создал несколько тестов. Я собираюсь представить вам их исходный код и результаты.

Microsoft Edge WebDriver

 

Пока в серии «WebDriver»

1.  Начало работы с WebDriver C # за 10 минут

2.  Наиболее недооцененный локатор WebDriver — XPath

3.  WebDriver Selenium Tor Интеграция C # Код

4.  Тест перенаправления URL с помощью WebDriver и HttpWebRequest

5.  Microsoft Edge WebDriver — все должны знать

6.  Ускорьте тесты Selenium, используя факты и мифы о RAM

 

Создайте свой первый тестовый проект WebDriver

1. Создать новый тестовый проект в Visual Studio.

Тестовый проект WebDriver

 

2. Установите   менеджер пакетов NuGet и перейдите к нему.

Откройте консоль управления NuGet

 

3. Найдите  Selenium  и  установите  первый элемент в списке результатов.

Установить пакет Selenium WebDriver

Код Microsoft Edge WebDriver C #

Test’s Test Case

Основная цель тестов, приведенных ниже, заключается в создании « здорового » диетического меню из специально разработанной   страницы генератора диеты .

Страница генератора здорового меню

 

Примеры кода в Firefox WebDriver

Автоматизация вышеуказанной формы с помощью Firefox WebDriver является тривиальной задачей.

[TestClass]
public class HealthyDietMenuGeneratorTestsFirefox
{
    private IWebDriver driver { get; set; }

    [TestInitialize]
    public void SetupTest()
    {
        this.driver = new FirefoxDriver();
    }

    [TestCleanup]
    public void TeardownTest()
    {
        this.driver.Quit();
    }

    [TestMethod]
    public void FillAwsomeDietTest()
    {
        this.driver.Navigate().GoToUrl(@"http://automatetheplanet.com/healthy-diet-menu-generator/");
        var addAdditionalSugarCheckbox = this.driver.FindElement(By.Id("ninja_forms_field_18"));
        addAdditionalSugarCheckbox.Click();
        var ventiCoffeeRadioButton = this.driver.FindElement(By.Id("ninja_forms_field_19_1"));
        ventiCoffeeRadioButton.Click();
        SelectElement selectElement = new SelectElement(this.driver.FindElement(By.XPath("//*[@id='ninja_forms_field_21']")));
        selectElement.SelectByText("7 x BBQ Ranch Burgers");
        var smotheredChocolateCakeCheckbox = this.driver.FindElement(By.Id("ninja_forms_field_27_2"));
        smotheredChocolateCakeCheckbox.Click();
        var addSomethingToDietTextArea = this.driver.FindElement(By.Id("ninja_forms_field_22"));
        addSomethingToDietTextArea.SendKeys(@"Goi cuon- This snack made from pork, shrimp, herbs, rice vermicelli and other ingredients wrapped in rice paper is served at room temperature. It’s “meat light,” with the flavors of refreshing herbs erupting in your mouth.");
        var rockStarRating = this.driver.FindElement(By.XPath("//*[@id='ninja_forms_field_20_div_wrap']/span/div[11]/a"));
        rockStarRating.Click();
        var firstNameTextBox = this.driver.FindElement(By.Id("ninja_forms_field_23"));
        firstNameTextBox.SendKeys("Anton");
        var lastNameTextBox = this.driver.FindElement(By.Id("ninja_forms_field_24"));
        lastNameTextBox.SendKeys("Angelov");
        var emailTextBox = this.driver.FindElement(By.Id("ninja_forms_field_25"));
        emailTextBox.SendKeys("aangelov@yahoo.com");
        var awsomeDietSubmitButton = this.driver.FindElement(By.Id("ninja_forms_field_28"));
        awsomeDietSubmitButton.Click();
    }
}

Экземпляр драйвера создается в   методе TestSetup и располагается в  TestCleanup . После этого тест переходит на нужную страницу, находит указанные элементы и выполняет требуемое действие. Если вы не знаете, как использовать различные методы WebDriver, возможно, вам будет интересно мое краткое руководство по этому вопросу —  Начало работы с WebDriver C # за 10 минут .

Тест был выполнен в течение ~ 16 секунд.

Результаты выполнения диетического теста Firefox Driver

 

Примеры кода в Firefox WebDriver + объекты страницы

Я также переписал тест для использования PageDriver Page Objects. Я создал   класс HealthyDietGeneratorPage, в котором присутствуют все элементы.

public class HealthyDietGeneratorPage
{
    public readonly string Url = @"http://automatetheplanet.com/healthy-diet-menu-generator/";

    public HealthyDietGeneratorPage(IWebDriver browser)
    {
        PageFactory.InitElements(browser, this);
    }

    [FindsBy(How = How.Id, Using = "ninja_forms_field_18")]
    public IWebElement AddAdditionalSugarCheckbox { get; set; }

    [FindsBy(How = How.Id, Using = "ninja_forms_field_19_1")]
    public IWebElement VentiCoffeeRadioButton { get; set; }

    [FindsBy(How = How.XPath, Using = "//*[@id='ninja_forms_field_21']")]
    public IWebElement BurgersDropDown { get; set; }

    [FindsBy(How = How.Id, Using = "ninja_forms_field_27_2")]
    public IWebElement SmotheredChocolateCakeCheckbox { get; set; }

    [FindsBy(How = How.Id, Using = "ninja_forms_field_22")]
    public IWebElement AddSomethingToDietTextArea { get; set; }

    [FindsBy(How = How.XPath, Using = "//*[@id='ninja_forms_field_20_div_wrap']/span/div[11]/a")]
    public IWebElement RockStarRating { get; set; }

    [FindsBy(How = How.Id, Using = "ninja_forms_field_23")]
    public IWebElement FirstNameTextBox { get; set; }

    [FindsBy(How = How.Id, Using = "ninja_forms_field_24")]
    public IWebElement LastNameTextBox { get; set; }

    [FindsBy(How = How.Id, Using = "ninja_forms_field_25")]
    public IWebElement EmailTextBox { get; set; }

    [FindsBy(How = How.Id, Using = "ninja_forms_field_28")]
    public IWebElement AwsomeDietSubmitButton { get; set; }
} 

Когда объект создается впервые, все элементы инициализируются через PageFactory WebDriver .

Код теста практически идентичен, с той лишь разницей, что инициализация элементов теперь является обязанностью объекта страницы.

[TestClass]
public class HealthyDietMenuGeneratorTestsFirefox
{
    private IWebDriver driver { get; set; }

    [TestInitialize]
    public void SetupTest()
    {
        this.driver = new FirefoxDriver();
    }

    [TestCleanup]
    public void TeardownTest()
    {
        this.driver.Quit();
    }

    [TestMethod]
    public void FillAwsomeDietTest_ThroughPageObjects()
    {
        HealthyDietGeneratorPage healthyDietGeneratorPage = new HealthyDietGeneratorPage(this.driver);
        this.driver.Navigate().GoToUrl(healthyDietGeneratorPage.Url);
        healthyDietGeneratorPage.AddAdditionalSugarCheckbox.Click();
        healthyDietGeneratorPage.VentiCoffeeRadioButton.Click();
        SelectElement selectElement = new SelectElement(healthyDietGeneratorPage.BurgersDropDown);
        selectElement.SelectByText("7 x BBQ Ranch Burgers");
        healthyDietGeneratorPage.SmotheredChocolateCakeCheckbox.Click();
        healthyDietGeneratorPage.AddSomethingToDietTextArea.SendKeys(@"Goi cuon- This snack made from pork, shrimp, herbs, rice vermicelli and other ingredients wrapped in rice paper is served at room temperature. It’s “meat light,” with the flavors of refreshing herbs erupting in your mouth.");
        healthyDietGeneratorPage.RockStarRating.Click();
        healthyDietGeneratorPage.FirstNameTextBox.SendKeys("Anton");
        healthyDietGeneratorPage.LastNameTextBox.SendKeys("Angelov");
        healthyDietGeneratorPage.EmailTextBox.SendKeys("aangelov@yahoo.com");
        healthyDietGeneratorPage.AwsomeDietSubmitButton.Click();
    }
}

Время выполнения почти не изменилось — ~ 15 секунд. Во всяком случае, это было немного быстрее.

Результаты выполнения теста Объекты страницы Firefox WebDriver

 

Microsoft Edge WebDriver Предварительные условия

1.  Загрузите   исполняемый файл Microsoft Edge WebDriver с официального сайта Microsoft.

Загрузить Microsoft Edge WebDriver

 

2.  Установите Microsoft Edge WebDriver  из ранее загруженной установки.

Установите Microsoft Edge WebDriver

 

3.  Создайте  виртуальную машину или  обновите  свою ОС до  Windows 10 , Microsoft Edge WebDriver совместим только с ней.

Примеры кода в Microsoft Edge WebDriver

Теоретически, те же самые тесты должны выполняться через новый WebDriver, только с заменой типа драйвера. Настройка  Microsoft Edge WebDriver  немного сложнее. Также есть еще не поддерживаемые методы, такие как  GoToUrl  и FindElement от XPath . Переход к новому URL-адресу осуществляется с помощью   назначения this.driver.Url .

[TestClass]
public class HealthyDietMenuGeneratorTestsEdge
{
    public IWebDriver driver;
    private string serverPath = "Microsoft Web Driver";

    [TestInitialize]
    public void SetupTest()
    {
        if (System.Environment.Is64BitOperatingSystem)
        {
            serverPath = Path.Combine(System.Environment.ExpandEnvironmentVariables("%ProgramFiles(x86)%"), serverPath);
        }
        else
        {
            serverPath = Path.Combine(System.Environment.ExpandEnvironmentVariables("%ProgramFiles%"), serverPath);
        }
        EdgeOptions options = new EdgeOptions();
        options.PageLoadStrategy = EdgePageLoadStrategy.Eager;
        this.driver = new EdgeDriver(serverPath, options);

        //Set page load timeout to 5 seconds
        this.driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(5));
    }

    [TestCleanup]
    public void TeardownTest()
    {
        this.driver.Quit();
    }

    [TestMethod]
    public void FillAwsomeDietTest()
    {
        //this.Driver.Navigate().GoToUrl(@"http://automatetheplanet.com/healthy-diet-menu-generator/");
        this.driver.Url = @"http://automatetheplanet.com/healthy-diet-menu-generator/";
        var addAdditionalSugarCheckbox = this.driver.FindElement(By.Id("ninja_forms_field_18"));
        addAdditionalSugarCheckbox.Click();
        var ventiCoffeeRadioButton = this.driver.FindElement(By.Id("ninja_forms_field_19_1"));
        ventiCoffeeRadioButton.Click();
        //SelectElement selectElement = new SelectElement(this.Driver.FindElement(By.Id("ninja_forms_field_21")));
        //selectElement.SelectByText("7 x BBQ Ranch Burgers");
        var smotheredChocolateCakeCheckbox = this.driver.FindElement(By.Id("ninja_forms_field_27_2"));
        smotheredChocolateCakeCheckbox.Click();
        var addSomethingToDietTextArea = this.driver.FindElement(By.Id("ninja_forms_field_22"));
        addSomethingToDietTextArea.SendKeys(@"Goi cuon- This snack made from pork, shrimp, herbs, rice vermicelli and other ingredients wrapped in rice paper is served at room temperature. It’s “meat light,” with the flavors of refreshing herbs erupting in your mouth.");
        //var rockStarRating = this.Driver.FindElement(By.XPath("//*[@id='ninja_forms_field_20_div_wrap']/span/div[11]/a"));
        //rockStarRating.Click();
        var firstNameTextBox = this.driver.FindElement(By.Id("ninja_forms_field_23"));
        firstNameTextBox.SendKeys("Anton");
        var lastNameTextBox = this.driver.FindElement(By.Id("ninja_forms_field_24"));
        lastNameTextBox.SendKeys("Angelov");
        var emailTextBox = this.driver.FindElement(By.Id("ninja_forms_field_25"));
        emailTextBox.SendKeys("aangelov@yahoo.com");
        var awsomeDietSubmitButton = this.driver.FindElement(By.Id("ninja_forms_field_28"));
        awsomeDietSubmitButton.Click();
    }
}

Тот же тест, выполненный с драйвером Firefox, завершился за  16 секунд ; теперь он работал в течение  4 секунд с использованием нового  Microsoft Edge WebDriver .

Результаты тестирования Microsoft Edge WebDriver

 

Реализация объекта страницы была еще быстрее. Выполнение теста заняло всего 3 секунды.

[TestClass]
public class HealthyDietMenuGeneratorTestsEdge
{
    private IWebDriver driver;
    private string serverPath = "Microsoft Web Driver";

    [TestInitialize]
    public void SetupTest()
    {
        if (System.Environment.Is64BitOperatingSystem)
        {
            serverPath = Path.Combine(System.Environment.ExpandEnvironmentVariables("%ProgramFiles(x86)%"), serverPath);
        }
        else
        {
            serverPath = Path.Combine(System.Environment.ExpandEnvironmentVariables("%ProgramFiles%"), serverPath);
        }
        EdgeOptions options = new EdgeOptions();
        options.PageLoadStrategy = EdgePageLoadStrategy.Eager;
        this.driver = new EdgeDriver(serverPath, options);

        //Set page load timeout to 5 seconds
        this.driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(5));
    }

    [TestCleanup]
    public void TeardownTest()
    {
        this.driver.Quit();
    }

    [TestMethod]
    public void FillAwsomeDietTest_ThroughPageObjects()
    {
        HealthyDietGeneratorPage healthyDietGeneratorPage = new HealthyDietGeneratorPage(this.driver);
        //this.Driver.Navigate().GoToUrl(healthyDietGeneratorPage.Url);
        this.driver.Url = healthyDietGeneratorPage.Url;
        healthyDietGeneratorPage.AddAdditionalSugarCheckbox.Click();
        healthyDietGeneratorPage.VentiCoffeeRadioButton.Click();
        //SelectElement selectElement = new SelectElement(healthyDietGeneratorPage.BurgersDropDown);
        //selectElement.SelectByText("7 x BBQ Ranch Burgers");
        healthyDietGeneratorPage.SmotheredChocolateCakeCheckbox.Click();
        healthyDietGeneratorPage.AddSomethingToDietTextArea.SendKeys(@"Goi cuon- This snack made from pork, shrimp, herbs, rice vermicelli and other ingredients wrapped in rice paper is served at room temperature. It’s “meat light,” with the flavors of refreshing herbs erupting in your mouth.");
        //healthyDietGeneratorPage.RockStarRating.Click();
        healthyDietGeneratorPage.FirstNameTextBox.SendKeys("Anton");
        healthyDietGeneratorPage.LastNameTextBox.SendKeys("Angelov");
        healthyDietGeneratorPage.EmailTextBox.SendKeys("aangelov@yahoo.com");
        healthyDietGeneratorPage.AwsomeDietSubmitButton.Click();
    }
}

Исходный код

Вы можете скачать полный исходный код из моего  репозитория Github.

If you enjoy my publications, feel free to SUBSCRIBE– http://automatetheplanet.com/newsletter/ Also, hit these share buttons. Thank you!