注:demo 仅供学习使用
demo 实例为登录测试,通过java -D变量=变量值的方式实现动态传参;IP/域名&Port&账号&密码;
下面是demo;
1)、Base.java:基类,封装selenium grid 数据
import org.apache.commons.io.FileUtils; import org.openqa.selenium.*; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.firefox.FirefoxOptions; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import org.testng.annotations.DataProvider; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import java.util.NoSuchElementException; /** * @time 2018-06-28 * @author tangyongchun * @description 封装selenium grid 数据 * */ public class Base { public static WebDriver driver; /** * 通过testNG提供的注解,实现数据驱动 * * @return */ @DataProvider(name = "data") public Object[][] data() { return new Object[][] { { "http://192.168.38.156:5555", "chrome" } }; } /** * 获取对应的数据源 * * @param nodeUrl * 节点地址 * @param browser * 节点浏览器 * @throws MalformedURLException */ public static void initDriver(String nodeUrl, String browser) throws MalformedURLException { DesiredCapabilities desiredCapabilities = null; // 拼接要执行的节点地址 String url = nodeUrl + "/wd/hub"; switch (browser) { case "chrome": ChromeOptions chromeOptions = new ChromeOptions(); driver = new RemoteWebDriver(new URL(url), chromeOptions); break; case "firefox": driver = new RemoteWebDriver(new URL(url), new FirefoxOptions()); break; case "ie": desiredCapabilities = DesiredCapabilities.internetExplorer(); driver = new RemoteWebDriver(new URL(url), desiredCapabilities); break; default: System.out.println("未知"); break; } } public boolean isElementPresent(By by) { try { driver.findElement(by); return true; } catch (NoSuchElementException e) { return false; } } public boolean isAlertPresent() { try { driver.switchTo().alert(); return true; } catch (NoAlertPresentException Ex) { return false; } } public String getAlert() { Alert alert = driver.switchTo().alert(); String str = alert.getText(); alert.accept(); return str; } public void snapShot(String Des) throws Exception { File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); String pathScreen ="/test-output/snapShot/Base/" + Des + ToolUtil.getCurrentDate("MMddHHmmss") + ".png"; FileUtils.copyFile(srcFile, new File(pathScreen)); } }
2)、Log.java:日志,视情况使用
import org.apache.log4j.Level; import org.apache.log4j.Logger; public class Log { public static final Log infoLog = new Log("info"); public static final Log errorLog = new Log("error"); public static final Log reportLog = new Log("report"); private Logger logger; private String prefix = ""; private boolean isLogEnabled; public Log() { } public Log(String name) { this(name, null); isLogEnabled = true; } public Log(String name, String prefix) { logger = Logger.getLogger(name); setPrefix(prefix); } public void setPrefix(String prefix) { if (prefix != null && prefix.length() > 0) this.prefix += "[" + prefix + "]"; } public boolean isDebugEnabled() { return logger.isEnabledFor(Level.DEBUG); } public boolean isInfoEnabled() { return logger.isEnabledFor(Level.INFO); } public boolean isWarnEnabled() { return logger.isEnabledFor(Level.WARN); } public boolean isErrorEnabled() { return logger.isEnabledFor(Level.ERROR); } public boolean isFatalEnabled() { return logger.isEnabledFor(Level.FATAL); } public void debug(Object object, Throwable throwable) { if (logger.isEnabledFor(Level.DEBUG)&&isLogEnabled) logger.debug(wrap(object), throwable); } public void debug(Object object) { if (logger.isEnabledFor(Level.DEBUG)&&isLogEnabled) logger.debug(wrap(object)); } public void info(Object object, Throwable throwable) { if (logger.isEnabledFor(Level.INFO)&&isLogEnabled) logger.info(wrap(object), throwable); } public void info(Object object) { if (logger.isEnabledFor(Level.INFO)&&isLogEnabled) logger.info(wrap(object)); } public void warn(Object object, Throwable throwable) { if (logger.isEnabledFor(Level.WARN)&&isLogEnabled) logger.warn(wrap(object), throwable); } public void warn(Object object) { if (logger.isEnabledFor(Level.WARN)&&isLogEnabled) logger.warn(wrap(object)); } public void error(Object object, Throwable throwable) { if (logger.isEnabledFor(Level.ERROR)&&isLogEnabled) logger.error(wrap(object), throwable); } public void error(Object object) { if (logger.isEnabledFor(Level.ERROR)&&isLogEnabled) logger.error(wrap(object)); } public void fatal(Object object, Throwable throwable) { if (logger.isEnabledFor(Level.FATAL)&&isLogEnabled) logger.fatal(wrap(object), throwable); } public void fatal(Object object) { if (logger.isEnabledFor(Level.FATAL)&&isLogEnabled) logger.fatal(wrap(object)); } private Object wrap(Object object) { if (prefix != null) return (new StringBuilder(String.valueOf(prefix))).append(object).toString(); else return object; } public void setLogEnabled(boolean enabled) { this.isLogEnabled = enabled; } public boolean isLogEnabled() { return isLogEnabled; } }
3)ToolUtil :工具类
import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.List; public class ToolUtil { public static String getCurrentDate(String format) { Calendar day = Calendar.getInstance(); day.add(Calendar.DATE, 0); SimpleDateFormat sdf = new SimpleDateFormat(format);// "yyyy-MM-dd HH:mm:ss" String date = sdf.format(day.getTime()); return date; } public static boolean compareList(List<String> listA,List<String> listB){ boolean reslut=false; for(int i=0;i<listA.size();i++){ if(!(listA.get(i).equals(listB.get(i)))){ reslut=false; break; }else reslut=true; } return reslut; } }
4)Login.java :selenium 实现模拟登录
import org.openqa.selenium.By; public class Login extends Base { public void loginInfo(String username, String password) throws Exception { // 避免计算机记住其他用户名密码的情况 driver.findElement(By.className("uName")).clear(); driver.findElement(By.className("uName")).sendKeys(username); driver.findElement(By.className("pwd")).clear(); driver.findElement(By.className("pwd")).sendKeys(password); Thread.sleep(1000); driver.findElement(By.className("login-btn")).click(); Thread.sleep(1000); // 验证登陆是否成功 if (isElementPresent(By.linkText("退出"))) { Log.reportLog.info("登陆成功"); } } public void logoutInfo() throws Exception { driver.findElement(By.linkText("退出")).click(); Thread.sleep(1000); driver.quit(); } }
5)LoginTest.java:登录测试类
import org.testng.annotations.Parameters; import org.testng.annotations.Test; import java.net.MalformedURLException; import java.util.concurrent.TimeUnit; public class LoginTest extends Base { private String url = ""; private String username = ""; private String passwd = ""; @Test(dataProvider = "data") public void login(String nodeUrl, String browser) throws MalformedURLException { initDriver(nodeUrl, browser); driver.get(url); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); String nowDate = ToolUtil.getCurrentDate("yyyy-MM-dd HH:mm:ss"); Log.reportLog.info("开始执行脚本,时间:" + nowDate); Login lg = new Login(); try { lg.loginInfo(username, passwd); Thread.sleep(5000); driver.quit(); lg.logoutInfo(); } catch (Exception e) { Log.errorLog.error(e.getMessage()); } } /** * 获取xml文件中测参数值 * * @param url * @param username * @param passwd */ @Test @Parameters({ "url", "username", "passwd" }) public void getParameters(String url, String username, String passwd) { this.url = url; this.username = username; this.passwd = passwd; } }
6)suite.xml:TestNg 执行测试文件
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd" > <suite name="ci"> <listeners> <listener class-name="org.uncommons.reportng.HTMLReporter" /> <listener class-name="org.uncommons.reportng.JUnitXMLReporter" /> </listeners> <test name="登录验证"> <parameter name="url" value="http://${hip}:${hport}/login.html" /> <parameter name="username" value="${username}" /> <parameter name="passwd" value="${passwd}" /> <classes> <class name="LoginTest" /> </classes> </test> </suite>