操作下拉列表
<html> <head> <title>下拉菜单</title> </head> <body> <select name='fruit' size=1> <option id='peach' value='taozi'>桃子</option> <option id='watermelon' value='xigua'>西瓜</option> <option id='orange' value='juzi'>橘子</option> <option id='kiwifruit' value='mihoutao'>猕猴桃</option> <option id='maybush' value='shanzha'>山楂</option> <option id='litchi' value='lizhi'>荔枝</option> </select> </body> </html>
package cn.gloryroad; import org.testng.annotations.Test; import org.testng.annotations.BeforeMethod; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.Select; import org.testng.Assert; import org.testng.annotations.AfterMethod; public class ApiTest5 { public WebDriver driver; String baseUrl; @Test public void f() { File file=new File("D:\workspace\WebDriver-API\src\dropList.html"); String filepath=file.getAbsolutePath(); driver.get(filepath); Select dropList= new Select(driver.findElement(By.name("fruit"))); List<String>expect_options=Arrays.asList(new String[]{"桃子","西瓜","橘子","猕猴桃","山楂","荔枝"}); List<String>actual_options=new ArrayList<String>(); List<WebElement>options=dropList.getOptions(); for(WebElement option: options){ actual_options.add(option.getText()); }System.out.println(actual_options); Assert.assertEquals(expect_options.toArray(), actual_options.toArray()); // dropList.selectByVisibleText("荔枝"); // Assert.assertEquals("荔枝", dropList.getFirstSelectedOption().getText()); } @BeforeMethod public void beforeMethod() { System.setProperty("webdriver.chrome.driver", "C:\chromedriver\chromedriver.exe"); driver= new ChromeDriver(); } @AfterMethod public void afterMethod() { try{ Thread.sleep(3000); }catch(InterruptedException e){ e.printStackTrace(); } driver.quit(); } }