2013-07-19 4 views
2
WebElement select = myD.findElement(By.xpath("//*[@id='custfoodtable']/tbody/tr[2]/td/div/select")); 
List<WebElement> allOptions = select.findElements(By.tagName("option")); 
for (WebElement option : allOptions) { 
    System.out.println(String.format("Value is: %s", option.getAttribute("value"))); 
    option.click(); 
    Object vaLue = "Gram"; 
    if (option.getAttribute("value").equals(vaLue)) { 
     System.out.println("Pass"); 
    } else { 
     System.out.println("fail"); 
    } 
} 

목록에서 하나의 요소를 확인할 수 있지만 확인해야하는 드롭 다운에 20 개의 요소가 있으며 위의 논리를 20 번 사용하지 않으려합니다. 더 쉬운 방법이 있습니까?목록 요소를 Selenium WebDriver로 확인하십시오.

+0

인쇄 결과는 무엇인가? –

답변

4

for-each 구문을 사용하지 마십시오. 단일 Iterable/배열을 반복 할 때만 유용합니다. List<WebElement> 및 배열을 동시에 반복해야합니다. 영업 이익의 후

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

편집 그의 질문 약간 변경 :

예상 값의 배열을 가지고 가정을, 당신은이 작업을 수행 할 수 있습니다

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

이 코드는 기본적으로 무엇을합니까 내 첫 번째 코드가 그랬다. 유일한 차이점은 작업을 수동으로 수행하고 결과를 인쇄한다는 것입니다.

이전에는 JUnit 프레임 워크의 Assert 클래스의 assertEquals() 정적 메서드를 사용했습니다. 이 프레임 워크는 Java 테스트를 작성하는 데있어 사실상의 표준이며, assertEquals() 메소드 패밀리가 프로그램 결과를 검증하는 표준 방법입니다. 그들은 메소드에 전달 된 인수가 동일한지 확인하고 그렇지 않은 경우 AssertionError을 던집니다.

어쨌든 수동 방식으로도 문제가 없습니다.

+0

대답 녀석 주셔서 감사합니다.하지만 난 내가 cauz 이해한다면 나는 알지 못한다. 나는이 일에 아주 익숙하다. 사실 나는 이것을 시도했습니다 – user2502733

+0

이 코드는 for-each 루프 대신에 있어야합니다. 필요한 경우 인쇄물을 포함 할 수 있습니다. 즉, 이것이 필요에 따라 정확히 작동해야하며, '

+0

이봐, 난 그냥 내 질문을 변경 비트. 일찍 혼란 한 것에 대해 유감스럽게 생각합니다. 목록에있는 모든 요소를 ​​확인하는 쉬운 방법이 있는지보고 싶습니다. – user2502733

1

당신은 이런 식으로 작업을 수행 할 수 있습니다

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()); 
관련 문제