在selenium webdriver中,验证所有产品是否按名称排序

时间:2015-07-11 13:55:36

标签: selenium webdriver

在Selenium WebDriver中,如果我按名称'选择下拉值。那么如何验证所有产品是否按名称排序?

这是我的代码:

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

public class Magneto
{

    public static void main(String[] args) throws Exception {

        WebDriver d1 = new FirefoxDriver();
        d1.navigate().to("http://live.guru99.com/index.php/");
        d1.manage().window().maximize();
        if (d1.getTitle().equals("Home page")) {
            System.out.println("title matched");
        } else {
            System.out.println("title not matched expected title is "
                + d1.getTitle());
        }
        d1.findElement(By.xpath("//nav[@id='nav']/ol/li[1]/a")).click();
        Thread.sleep(2000);
        if (d1.getTitle().equals("Mobile")) {
            System.out.println("title matched");
        } else {
            System.out.println("title not matched expected title is "
                + d1.getTitle());
        }
        Select s1 = new Select(d1.findElement(By.xpath("//html[@id='top']/body/div[1]/div/div[2]/div/div[2]/div[1]/div[3]/div[1]/div[1]/div/select")));
        s1.selectByVisibleText("Name");}}

5 个答案:

答案 0 :(得分:1)

String sortElement = driver.findElement(By.xpath("//li[1]//a[@class=\"product-image\"]")).getAttribute("title");
Assert.assertEquals(sortElement, "IPhone");
sortElement = driver.findElement(By.xpath("//li[2]//a[@class=\"product-image\"]")).getAttribute("title");
Assert.assertEquals(sortElement, "Samsung Galaxy");
sortElement = driver.findElement(By.xpath("//li[3]//a[@class=\"product-image\"]")).getAttribute("title");
Assert.assertEquals(sortElement, "Xperia");

答案 1 :(得分:0)

将以下代码添加到主方法

//create an LinkedList instead of arraylist because it preserves insertion order

List<WebElement> products_Webelement = new LinkedList<WebElement>();

//store the products (web elements) into the linkedlist

products_Webelement = d1.findElements(By.xpath("//img[contains(@id, 'product-collection-image')]"));

//create another linked list of type string to store image title

LinkedList<String> product_names =  new LinkedList<String>();

//loop through all the elements of the product_webelement list get it title and store it into the product_names list

for(int i=0;i<products_Webelement.size();i++){

    String s = products_Webelement.get(i).getAttribute("alt");

    product_names.add(s);

}

//send the list to chkalphabetical_order method to check if the elements in the list are in alphabetical order    

boolean result = chkalphabetical_order(product_names);


//print the result    

System.out.println(result);

在方法chkalphabetical_order中,我们使用compareTo方法检查元素是否按字母顺序排列,因为java中的字符串类实现了Comparable,并且将使用字符串自然顺序进行比较。如果元素在,则此方法将返回true按字母顺序返回false

    public static boolean chkalphabetical_order(LinkedList<String> product_names){

    String previous = ""; // empty string

    for (final String current: product_names) {
        if (current.compareTo(previous) < 0)
            return false;
        previous = current;
    }

    return true;

    }

希望这会对你有所帮助。我测试了上面的代码,它工作得很完美。如果你有任何疑问,请回来

答案 2 :(得分:0)

我有一个场景,我必须验证排序菜单

try{
        List<WebElement> lst = driver.findElements(By
                .xpath(".//*[@id='global-wrapper']/nav/ul/li"));
        String[] str = new String[lst.size()];
        String[] ORGstr = new String[lst.size()];

    int i = 0;
    int l = 0;
    for (WebElement ele1 : lst) {
        if (ele1.getText() != null)
            ORGstr[l] = ele1.getText();
        l++;
    }

    for (WebElement ele : lst) {
        if (ele.getText() != null)
            str[i] = ele.getText();
        i++;
    }

    for (int b = 0; b < str.length; b++) {

        for (int j = b + 1; j < str.length; j++) {
            if (str[b].compareTo(str[j]) > 0) {
                String temp = str[b];
                str[b] = str[j];
                str[j] = temp;
            }

        }
    }
    int o = 1;
    int s = 0;

    for (int k = 0; k < str.length; k++) {
        //System.out.println("Sorted Order " + str[s] + " ");
        //System.out.println("Original Order " + ORGstr[o] + " ");
        if (!(str[s].equalsIgnoreCase("Dashboard"))) {
            if (str[s].equalsIgnoreCase(ORGstr[o])) {
                assertEquals(str[s], ORGstr[o]);
                o++;
                log.debug("verified dashboard menu is sorted");
            } else {

                Assert.fail();
            }
        }
        s++;

    }

    }catch(Exception e){

        ErrorLog.fatal("Error: Element not located in menu");   
    }

在我的代码中,我不得不跳过一个名为dashboard的菜单项,我根据我的要求写了它,你可以相应改变!!!!

答案 3 :(得分:0)

List<WebElement> li=new LinkedList<>(obj.findElements(By.xpath("//h2[@class='product-name']/a")));    
        LinkedList<String> pn=new LinkedList<String>();    
        for(int i=0;i<li.size();i++)    
        {    
             //just displaying the product names    
            //System.out.println(li.get(i).getText());    
            pn.add(li.get(i).getText());    
        }    
        boolean result = comp_order(pn);    

you need to add one more method    

//alphabetical order checking    
    public static boolean comp_order(LinkedList<String> pn)    
    {           
        String prev=""; // empty string    
        for (final String cur: pn)    
        {    
            if (cur.compareTo(prev) < 0)    
            {      
                return false;     
            }    
            prev=cur;    
        }    
        return true;    
        }    

i did nothing just improved previous solution its working    

答案 4 :(得分:0)

如果Products的名称以小写字母和大写字母开头,则此排序方法将失败。

如果你跑,并检查

public class Testing
{
    public static void main(String[] args)
    {
        String name1= "pro";
        String name2= "TestPro";
        int tmp=name2.compareTo(name1);
        System.out.println(tmp);
    }
} 
Output: -28

虽然,我们期待它返回一些正整数。

因此,要解决此问题,我们需要将所有名称转换为小写,然后检查它们是否已排序?

我是这样做的,我的代码还有其他一些你可以忽略的功能。

public class SortingTest 
{
    static WebDriver driver;

    @Test
    public static void AnchorTags() throws InterruptedException
    {

        driver=new ChromeDriver();
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
        Thread.sleep(5000);
        driver.get("http://xyz21314131.co");

        driver.findElement(By.linkText("Ascending Order")).click();
        Thread.sleep(5000);
        WebElement Row=driver.findElement(By.xpath("//* [@id='content']/div/div[2]"));
        List<WebElement> Anchortags=Row.findElements(By.tagName("a"));

        //Linked List to Store ProductNames
        LinkedList<String> productNames=new LinkedList<String>();

        int size=Anchortags.size();

        for(WebElement temp:Anchortags)
        {
            String sTemp=temp.getText();
          //Important
           **// to remove extra spaces and to Lowercase Every product name**
            productNames.add(sTemp.toLowerCase().trim());           
        }
        System.out.println(productNames);


        //Check SortedOr NOt?

        Boolean num=checkDescendingOrder(productNames);
        System.out.println("boolean value"+ num);
        if(num==true)
        {

            System.out.println("Products names are Sorted in ascending Order");
        }
        else {
            System.out.println("Products names are not Sorted in ascending Order");
            }
        System.out.println("New List:--"+productNames);
        System.out.println("Size is " + size);
    }

public static boolean checkAscendingOrder(LinkedList<String> Names)
{
    String previous = ""; // empty string

    for (String current: Names) {
        if (current.compareTo(previous) < 0)
        {
            return false;
        }
        previous = current;
    }
    return true;
    }   
}