Selenium 简明教程
Selenium - Multi Browser Testing
用户可以同时在多个浏览器中执行脚本。出于演示目的,我们将使用与 Selenium Grid 相同的场景。在 Selenium Grid 示例中,我们已经远程执行了脚本;在这里我们将本地执行脚本。
首先,确保您下载了合适的驱动程序。有关下载 IE 和 Chrome 驱动程序,请参阅“Selenium Grid”一章。
Example
为了演示,我们将在所有浏览器中同时执行百分比计算器。
package TestNG;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import org.testng.annotations.*;
public class TestNGClass {
private WebDriver driver;
private String URL = "http://www.calculator.net";
@Parameters("browser")
@BeforeTest
public void launchapp(String browser) {
if (browser.equalsIgnoreCase("firefox")) {
System.out.println(" Executing on FireFox");
driver = new FirefoxDriver();
driver.get(URL);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
} else if (browser.equalsIgnoreCase("chrome")) {
System.out.println(" Executing on CHROME");
System.out.println("Executing on IE");
System.setProperty("webdriver.chrome.driver", "D:\\chromedriver.exe");
driver = new ChromeDriver();
driver.get(URL);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
} else if (browser.equalsIgnoreCase("ie")) {
System.out.println("Executing on IE");
System.setProperty("webdriver.ie.driver", "D:\\IEDriverServer.exe");
driver = new InternetExplorerDriver();
driver.get(URL);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
} else {
throw new IllegalArgumentException("The Browser Type is Undefined");
}
}
@Test
public void calculatepercent() {
// Click on Math Calculators
driver.findElement(By.xpath(".//*[@id = 'menu']/div[3]/a")).click();
// Click on Percent Calculators
driver.findElement(By.xpath(".//*[@id = 'menu']/div[4]/div[3]/a")).click();
// Enter value 10 in the first number of the percent Calculator
driver.findElement(By.id("cpar1")).sendKeys("10");
// Enter value 50 in the second number of the percent Calculator
driver.findElement(By.id("cpar2")).sendKeys("50");
// Click Calculate Button
driver.findElement(By.xpath(".//*[@id = 'content']/table/tbody/tr/td[2]/input")).click();
// Get the Result Text based on its xpath
String result =
driver.findElement(By.xpath(".//*[@id = 'content']/p[2]/span/font/b")).getText();
// Print a Log In message to the screen
System.out.println(" The Result is " + result);
if(result.equals("5")) {
System.out.println(" The Result is Pass");
} else {
System.out.println(" The Result is Fail");
}
}
@AfterTest
public void closeBrowser() {
driver.close();
}
}
创建一个 XML,它将帮助我们对浏览器名称参数化,并且不要忘记提及 parallel="tests" 才能在所有浏览器中同时执行。
右键单击 XML 文件并选择“作为”>>“TestNG”套件运行脚本,如下所示。