在远程控制搭建完成之后,我新增了一台node机,期望值是2台node机同时运行我的代码,但是发现由于IP地址在 RemoteWebDriverUtil 中写死了,使用不灵活,在网上查到另一种使用@DataProvider驱动的方法。具体可以参考 http://www.360doc.com/content/16/1121/14/36343398_608254453.shtml 的后半部分。
将RemoteWebDriverUtil类中的3个方法通过传参的方式合并为一个方法:
package test; import java.net.MalformedURLException; import java.net.URL; import org.junit.Test; import org.openqa.selenium.Platform; import org.openqa.selenium.WebDriver; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import org.testng.annotations.DataProvider; public class RemoteWebDriverUtil { static WebDriver driver; public static WebDriver createRemoteDriver(String nodeURL,String Broswer) { DesiredCapabilities capability; if(Broswer.toLowerCase().equals("chrome")){ capability = DesiredCapabilities.chrome(); capability.setBrowserName("chrome"); capability.setVersion("62"); }else if (Broswer.toLowerCase().equals("firefox")) { capability = DesiredCapabilities.firefox(); capability.setBrowserName("firefox"); }else { capability = DesiredCapabilities.internetExplorer(); // 避免IE安全设置里,各个域的安全级别不一致导致的错误 capability.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true); } capability.setPlatform(Platform.XP); nodeURL = nodeURL+"/wd/hub"; try { driver = new RemoteWebDriver(new URL(nodeURL), capability); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return driver; } }
修改之前的test.java类:(顺便把名字也改了:))
package test; import java.text.SimpleDateFormat; import java.util.Date; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class GridDemo extends RemoteWebDriverUtil { public static final SimpleDateFormat Date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSS"); @DataProvider(name="data",parallel=true) public Object[][] data(){ return new Object[][]{{"http://10.65.254.30:3333", "chrome"}, {"http://10.65.254.15:5555", "chrome"} }; } @Test(enabled=true, dataProvider="data") public void testBaiduSearch(String nodeURL, String broswer) throws Exception{ System.out.println(Thread.currentThread().getId()+"-----------------------"+Date.format(new Date()));//打印线程启动时间 WebDriver driver = createRemoteDriver(nodeURL,broswer); driver.get("http://www.baidu.com"); WebElement baiduInput = driver.findElement(By.id("kw")); baiduInput.sendKeys("Cherry_chrome"); //此处自行增加后续操作 } }
修改TestNG.xml
<?xml version="1.0" encoding="UTF-8"?> <suite name="Suite" parallel="methods" thread-count="5" data-provider-thread-count="10"> <test name="Test"> <classes> <class name="test.GridDemo"/> </classes> </test> <!-- Test --> </suite> <!-- Suite -->
重新运行之后,2台node机同时运行testBaiduSearch方法,达到了分布式测试搭建的目的,整个搭建暂时结束