Как внедрить цикл while в тест на селен c # - PullRequest
0 голосов
/ 25 июня 2018

Я написал код, который отправляется на веб-сайт, ищет предмет, затем выбирает размер предмета и добавляет его в сумку.

После того, как предмет добавлен в сумку, я хочу ввести цикл while, чтобы он продолжал увеличивать количество предмета до тех пор, пока он не станет равным или превысит £ 200. Я понимаю, что цикл while будет лучшим способом для этого, поскольку я не знаю, какое количество циклов я хочу сделать.

Я полагаю, что петля должна быть введена, как только один предмет был добавлен в сумку, поскольку только в этот момент я могу сказать количество предмета. В моем цикле, как я могу получить свой код для проверки цены количества товаров при каждом увеличении на + 1.

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.Interactions;
using System.Threading;

namespace Exercise1
{
    class Exercise3
    {

        static void Main()
        {
            IWebDriver webDriver = new ChromeDriver();




            webDriver.Navigate().GoToUrl("http://www.asos.com/men/");
            webDriver.Manage().Window.Maximize();

            webDriver.FindElement(By.XPath(".//input[@data-testid='search-input']")).SendKeys("nike trainers");

            webDriver.FindElement(By.XPath(".//button[@data-testid='search-button-inline']")).Click();

            WebDriverWait wait = new WebDriverWait(webDriver, TimeSpan.FromSeconds(5));
            IWebElement country = wait.Until(ExpectedConditions.ElementExists(By.CssSelector("article img")));


            webDriver.FindElement(By.CssSelector("article img")).Click();


            IWebElement Size = webDriver.FindElement(By.XPath(".//select[@data-id='sizeSelect']"));
            SelectElementFromDropDown(Size, "UK 10.5 - EU 45.5 - US 11.5");


            webDriver.FindElement(By.XPath("//*[@data-bind='text: buttonText']")).Click();

            webDriver.FindElement(By.XPath("//a[@data-testid='bagIcon']")).Click();


    // I believe the while loop should be implemented here
            int number = 200;
            while (number > 200)

            webDriver.Quit();
        }

        private static void SelectElementFromDropDown(IWebElement ele, string text)
        {
            SelectElement select = new SelectElement(ele);
            select.SelectByText(text);
        }




    }

}

Ответы [ 3 ]

0 голосов
/ 25 июня 2018

Ниже код можно добавить в том месте, где вы прокомментировали // I believe the while loop should be implemented here

String price = webDriver.FindElement(By.XPath("//span[@class='bag-item-price bag-item-price--current']"))
            .getAttribute("innerHTML");
int pricePerUnit = (int) Double.Parse(price.substring(1, price.Length - 1));
int qty = 1;
while (pricePerUnit * qty <= 200) {
    qty++;
}
qty--;
IWebElement quantityDropDown = webDriver.FindElement(
        By.XPath("//select[@class='bag-item-quantity bag-item-selector select2-hidden-accessible']"));
SelectElementFromDropDown(quantityDropDown, qty.ToString());
0 голосов
/ 25 июня 2018

Вы можете реализовать свой сценарий, не используя циклы (цикл for / while). Я добавил логику ниже. Рендеринг некоторых элементов занимает больше времени. Итак, я бы предложил добавить явное условие, где это необходимо.

Пожалуйста, найдите обновленный код и отошлите все комментарии для более подробной информации

Основной метод:

            IWebDriver webDriver = new ChromeDriver();
            webDriver.Navigate().GoToUrl("http://www.asos.com/men/");
            webDriver.Manage().Window.Maximize();
            webDriver.FindElement(By.XPath(".//input[@data-testid='search-input']")).SendKeys("nike trainers");
            webDriver.FindElement(By.XPath(".//button[@data-testid='search-button-inline']")).Click();

            //Search Result rendering will take some times.So, Explicit wait is mandatory
            WebDriverWait wait = new WebDriverWait(webDriver, TimeSpan.FromSeconds(5));
            IWebElement country = wait.Until(ExpectedConditions.ElementExists(By.CssSelector("article img")));
            webDriver.FindElement(By.CssSelector("article img")).Click();

            IWebElement Size = webDriver.FindElement(By.XPath(".//select[@data-id='sizeSelect']"));
            SelectElementFromDropDown(Size, "UK 10 - EU 45 - US 11");

            webDriver.FindElement(By.XPath("//*[@data-bind='text: buttonText']")).Click();

            //Add to cart takes some time.So, the below condition is needed 
            wait.Until(ExpectedConditions.ElementExists(By.XPath("//span[text()='Added']")));

            webDriver.FindElement(By.XPath("//a[@data-testid='bagIcon']")).Click();
            //Wait condition is needed after the page load
            //wait.Until(ExpectedConditions.TitleContains("Shopping"));

            wait.Until(ExpectedConditions.ElementExists(By.XPath("//select[contains(@class,'bag-item-quantity')]")));
            //Extract the price from the cart
            string totalPrice =webDriver.FindElement(By.XPath("//span[@class='bag-subtotal-price']")).Text;
            //Extract the price amount by exluding the currency
            double pricePerItem = Convert.ToDouble(totalPrice.Substring(1));

            // Just hardcoded the expected price limit value
            int priceLimit = 200;

            double noOfQuantity = priceLimit / pricePerItem;

            IWebElement qty =webDriver.FindElement(By.XPath("//select[contains(@class,'bag-item-quantity')]"));
            //Quantity values are rounded off with nearest lowest value . Example, 5.55 will be considered as 5 quantity
            SelectElementFromDropDown(qty, Math.Floor(noOfQuantity).ToString());

            //After updating the quantity, update  button will be displayed dynamically.So, wait is added and then update action is performed
            wait.Until(ExpectedConditions.ElementExists(By.XPath("//button[@class='bag-item-edit-update']")));
            webDriver.FindElement(By.XPath("//button[@class='bag-item-edit-update']")).Click();

Альтернативный подход с использованием цикла:

Я бы настоятельно рекомендовал использовать вышеуказанный подход. так как количество будет увеличиваться по одному за каждый раз, пока ценовой лимит не превысит 200

        //Extract the price from the cart
        string totalPrice = webDriver.FindElement(By.XPath("//span[@class='bag-subtotal-price']")).Text;
        double currentTotalPrice = Convert.ToDouble(totalPrice.Substring(1));
        double itemPerPrice = currentTotalPrice;

        // Just hardcoded the expected price limit value
        int priceLimit = 200;
        int quantity = 1;

        while(currentTotalPrice < priceLimit && priceLimit-currentTotalPrice > itemPerPrice)
        {
            wait.Until(ExpectedConditions.ElementExists(By.XPath("//select[contains(@class,'bag-item-quantity')]")));
            IWebElement qty = webDriver.FindElement(By.XPath("//select[contains(@class,'bag-item-quantity')]"));
            //Quantity values are rounded off with nearest lowest value . Example, 5.55 will be considered as 5 quantity
            SelectElementFromDropDown(qty, (++quantity).ToString());
            //After updating the quantity, update  button will be displayed dynamically.So, wait is added and then update action is performed
            wait.Until(ExpectedConditions.ElementExists(By.XPath("//button[@class='bag-item-edit-update']")));
            webDriver.FindElement(By.XPath("//button[@class='bag-item-edit-update']")).Click();

            wait.Until(ExpectedConditions.ElementExists(By.XPath("//span[@class='bag-subtotal-price']")));
            var temp = webDriver.FindElement(By.XPath("//span[@class='bag-subtotal-price']")).Text;

            currentTotalPrice = Convert.ToDouble(temp.Substring(1));
            Console.WriteLine("Current Price :" + currentTotalPrice);
        }
0 голосов
/ 25 июня 2018
Store the value of the item in a variable before starting the loop and creata a variable with initial value int i =1 and with every time loop runs increment the value by and multiply it by the original value and match is with the value with you fetch from the UI eveytime..
int i = 1
while(condition){
i++
//price for each iteration `enter code here`
i*price for 1 item = "value from the UI"
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...