登录账号参数化
登录账号参数化
Login.java
package com.gubai.selenium; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; 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.interactions.Actions; public class Login { public WebDriver driver; public void InitDriver() { String url = "http://www.imooc.com/"; System.setProperty("webdriver.chrome.driver", "C:\\driver\\chromedriver.exe"); driver = new ChromeDriver(); driver.get(url); driver.manage().window().maximize(); this.elemnet(By.id("js-signin-btn")).click(); } public void loginscript(String username,String userpass) throws Exception { this.InitDriver(); Thread.sleep(3000); WebElement user = this.elemnet(this.byStr("username")); user.isDisplayed(); WebElement password = this.elemnet(this.byStr("userpass")); password.isDisplayed(); WebElement loginButton = this.elemnet(this.byStr("loginbutton")); loginButton.isDisplayed(); user.sendKeys(username); password.sendKeys(userpass); loginButton.click(); Thread.sleep(3000); WebElement header = this.elemnet(this.byStr("header")); header.isDisplayed(); Actions actions = new Actions(driver); actions.moveToElement(header).perform();; String userInfo = this.elemnet(this.byStr("nameInfo")).getText(); System.out.println(userInfo); if(userInfo.equals("mushishi_xu1")) { System.out.println("登陆成功"); }else { System.out.println("登录失败"); } driver.close(); } /**封装By by **/ public By byStr(String username){ ProUtil properties = new ProUtil("element.properties"); String locator = properties.getPro(username); String locatorType =locator.split(">")[0]; String locatorValue = locator.split(">")[1]; if(locatorType.equals("id")) { return By.id(locatorValue); }else if(locatorType.equals("name")){ return By.name(locatorValue); }else if(locatorType.equals("className")){ return By.className(locatorValue); }else if(locatorType.equals("xpath")){ return By.className(locatorValue); }else{ return By.xpath(locatorValue); } } /** * 封装Element * **/ public WebElement elemnet(By by) { WebElement ele = driver.findElement(by); return ele; } public static void main(String[] args) throws Exception{ Login login = new Login(); //login.loginscript("18513199586","111111"); /** * key -value * username-password * **/ HashMap<String,String> user = new HashMap<String,String>(); user.put("18513199586", "test123"); user.put("609037724@qq.com", "test123"); Iterator us = user.entrySet().iterator(); while(us.hasNext()) { Map.Entry entry = (Map.Entry) us.next(); String username = entry.getKey().toString(); String password = entry.getValue().toString(); login.loginscript(username, password); } } }