Verify list elements by Selenium WebDriver

前端 未结 2 533
北荒
北荒 2020-12-18 14:58
WebElement select = myD.findElement(By.xpath(\"//*[@id=\'custfoodtable\']/tbody/tr[2]/td/div/select\"));
List allOptions = select.findElements(By.t         


        
相关标签:
2条回答
  • 2020-12-18 15:43

    Don't use the for-each construct. It's only useful when iterating over a single Iterable / array. You need to iterate over the List<WebElement> and the array simultaneously.

    // assert that the number of found <option> elements matches the expectations
    assertEquals(exp.length, allOptions.size());
    // assert that the value of every <option> element equals the expected value
    for (int i = 0; i < exp.length; i++) {
        assertEquals(exp[i], allOptions.get(i).getAttribute("value"));
    }
    

    EDIT after OP's changed his question a bit:

    Assuming you have an array of expected values, you can do this:

    String[] expected = {"GRAM", "OUNCE", "POUND", "MILLIMETER", "TSP", "TBSP", "FLUID_OUNCE"};
    List<WebElement> allOptions = select.findElements(By.tagName("option"));
    
    // make sure you found the right number of elements
    if (expected.length != allOptions.size()) {
        System.out.println("fail, wrong number of elements found");
    }
    // make sure that the value of every <option> element equals the expected value
    for (int i = 0; i < expected.length; i++) {
        String optionValue = allOptions.get(i).getAttribute("value");
        if (optionValue.equals(expected[i])) {
            System.out.println("passed on: " + optionValue);
        } else {
            System.out.println("failed on: " + optionValue);
        }
    }
    

    This code essentially does what my first code did. The only real difference is that now you're doing the work manually and are printing the results out.

    Before, I used the assertEquals() static method from the Assert class of the JUnit framework. This framework is a de-facto standard in writing Java tests and the assertEquals() method family is the standard way to verify the results of your program. They make sure the arguments passed into the method are equal and if they are not, they throw an AssertionError.

    Anyway, you can do it the manual way, too, no problem.

    0 讨论(0)
  • 2020-12-18 15:50

    You can do it like this:

    String[] act = new String[allOptions.length];
    int i = 0;
    for (WebElement option : allOptions) {
        act[i++] = option.getValue();
    }
    
    List<String> expected = Arrays.asList(exp);
    List<String> actual = Arrays.asList(act);
    
    Assert.assertNotNull(expected);
    Assert.assertNotNull(actual);
    Assert.assertTrue(expected.containsAll(actual));
    Assert.assertTrue(expected.size() == actual.size());
    
    0 讨论(0)
提交回复
热议问题