下面列出了org.openqa.selenium.remote.RemoteWebDriver#quit ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private Thread getClosingBrowsersThread() {
return new Thread("Quit the open browsers") {
@Override
public void run() {
isClosing = true;
CopyOnWriteArrayList<RemoteWebDriver> driversCopy = new CopyOnWriteArrayList<>(drivers);
for (Iterator<RemoteWebDriver> iterator = driversCopy.iterator(); iterator.hasNext();) {
RemoteWebDriver remoteWebDriver = iterator.next();
try {
remoteWebDriver.quit();
} catch (final Exception e) {
logger.error("Error quitting the browser", e);
}
}
}
};
}
@ParameterizedTest
@MethodSource("capabilitesProvider")
void testServer(Capabilities capabilities) throws MalformedURLException {
String serverUrl = String.format("http://localhost:%s/wd/hub/",
serverPort);
RemoteWebDriver driver = new RemoteWebDriver(new URL(serverUrl),
capabilities);
assertNotNull(driver);
driver.get("https://bonigarcia.github.io/selenium-jupiter/");
assertThat(driver.getTitle(),
containsString("JUnit 5 extension for Selenium"));
driver.quit();
assertNull(driver.getSessionId());
}
@Test
public void deployUseUndeployCheck() throws Exception {
// DO NOT RUN FROM ECLIPSE
// The test uses files from the target folder
setup(7778);
RemoteWebDriver driver = new RemoteWebDriver(Browser.CHROME.getDesiredCapabilities());
try {
driver.get("http://"+ getCurrentHostAddress() + ":7778/");
Assert.assertNotNull(driver.findElement(By.id("hello")));
} finally {
driver.close();
driver.quit();
}
shutdownAndVerify();
}
private RemoteWebDriver initBrowser() throws BrowserNotFoundException {
RemoteWebDriver driver = null;
driver = chooseDriver();
if (isClosing) { // In case the browser takes so long to start that the user closes CE and this
// method is called when the other windows are being closed
driver.quit();
driver = null;
} else {
drivers.add(driver);
}
return driver;
}
@Override
protected MobileDevice initMobile(IDevice iDevice, AppiumServer appiumServer) throws Exception {
String mobileId = iDevice.getSerialNumber();
Mobile mobile = new Mobile();
mobile.setPlatform(MobileDevice.PLATFORM_ANDROID);
mobile.setCreateTime(new Date());
mobile.setId(mobileId);
mobile.setSystemVersion(AndroidUtil.getAndroidVersion(AndroidUtil.getSdkVersion(iDevice)));
mobile.setName(AndroidUtil.getDeviceName(iDevice));
mobile.setCpuInfo(AndroidUtil.getCpuInfo(iDevice));
mobile.setMemSize(AndroidUtil.getMemSize(iDevice));
mobile.setEmulator(iDevice.isEmulator() ? Mobile.EMULATOR : Mobile.REAL_MOBILE);
String resolution = AndroidUtil.getResolution(iDevice); // 720x1280
String[] res = resolution.split("x");
mobile.setScreenWidth(Integer.parseInt(res[0]));
mobile.setScreenHeight(Integer.parseInt(res[1]));
AndroidDevice androidDevice = new AndroidDevice(mobile, iDevice, appiumServer);
// 小于android5.0使用stf远程真机方案,否则使用scrcpy方案
// 小于android5.0初始化driver需要指定app
if (!androidDevice.greaterOrEqualsToAndroid5()) {
log.info("[{}]开始安装minicap", mobileId);
MinicapInstaller minicapInstaller = new MinicapInstaller(iDevice);
minicapInstaller.install();
log.info("[{}]安装minicap成功", mobileId);
log.info("[{}]开始安装minitouch", mobileId);
MinitouchInstaller minitouchInstaller = new MinitouchInstaller(iDevice);
minitouchInstaller.install();
log.info("[{}]安装minitouch成功", mobileId);
// 安装一个测试apk,用于初始化appium driver
log.info("[{}]开始安装{}", mobileId, APIDEMOS_APK);
androidDevice.installApp(new File(APIDEMOS_APK));
log.info("[{}]安装{}完成", mobileId, APIDEMOS_APK);
}
DesiredCapabilities caps = new DesiredCapabilities();
caps.setCapability("skipServerInstallation", false);
caps.setCapability("skipDeviceInitialization", false);
caps.setCapability("skipUnlock", false);
caps.setCapability("skipLogcatCapture", false);
log.info("[{}]开始初始化appium", mobileId);
RemoteWebDriver driver = androidDevice.freshDriver(caps, true);
log.info("[{}]初始化appium完成", mobileId);
// 截图并上传到服务器
UploadFile uploadFile = androidDevice.screenshotThenUploadToServer();
mobile.setImgPath(uploadFile.getFilePath());
driver.quit();
return androidDevice;
}
@Override
protected MobileDevice initMobile(IDevice iDevice, AppiumServer appiumServer) throws Exception {
String mobileId = iDevice.getSerialNumber();
boolean isRealDevice = !iDevice.isEmulator();
Mobile mobile = new Mobile();
mobile.setPlatform(MobileDevice.PLATFORM_IOS);
mobile.setCreateTime(new Date());
mobile.setId(mobileId);
mobile.setName(IosUtil.getDeviceName(mobileId, isRealDevice));
mobile.setEmulator(isRealDevice ? Mobile.REAL_MOBILE : Mobile.EMULATOR);
if (isRealDevice) {
mobile.setSystemVersion(IosUtil.getRealDeviceSystemVersion(mobileId));
}
IosDevice iosDevice = new IosDevice(mobile, appiumServer);
log.info("[{}]开始初始化appium", mobileId);
RemoteWebDriver driver = iosDevice.freshDriver(null, true);
log.info("[{}]初始化appium完成", mobileId);
if (!isRealDevice) {
try {
AppiumDriver appiumDriver = (AppiumDriver) driver;
String sdkVersion = (String) appiumDriver.getSessionDetail("sdkVersion");
mobile.setSystemVersion(sdkVersion);
} catch (Exception e) {
log.warn("[{}]获取sdkVersion失败", mobileId, e);
}
}
// 有时window获取的宽高可能为0
while (true) {
Dimension window = driver.manage().window().getSize();
int width = window.getWidth();
int height = window.getHeight();
if (width > 0 && height > 0) {
mobile.setScreenWidth(width);
mobile.setScreenHeight(height);
break;
} else {
log.warn("[{}]未获取到正确的屏幕宽高: {}", mobileId, window);
}
}
// 截图并上传到服务器
UploadFile uploadFile = iosDevice.screenshotThenUploadToServer();
mobile.setImgPath(uploadFile.getFilePath());
driver.quit();
return iosDevice;
}
@Test
public void shouldOpenSafari() throws MalformedURLException {
/**
* In this section, we will configure our SauceLabs credentials in order to run our tests on saucelabs.com
*/
String sauceUserName = "SAUCE_USERNAME";
String sauceAccessKey = "SAUCE_ACCESS_KEY";
/**
* In this section, we will configure our test to run a specific
* browser/os combination in Sauce Labs
*/
DesiredCapabilities capabilities = new DesiredCapabilities();
//set your user name and access key to run tests in Sauce
capabilities.setCapability("username", sauceUserName);
//set your sauce labs access key
capabilities.setCapability("accessKey", sauceAccessKey);
//set browser to Safari
capabilities.setCapability("browserName", "Safari");
//set operating system to macOS version 10.13
capabilities.setCapability("platform", "macOS 10.13");
//set the browser version to 11.1
capabilities.setCapability("version", "11.1");
//set the build name of the application
capabilities.setCapability("build", "Onboarding Sample App - Java-TestNG");
//set your test case name so that it shows up in Sauce Labs
capabilities.setCapability("name", "1-first-test");
/**
* In this section, we will set the WebDriver to a Remote driver to run on sauce, and pass the capabilities
* we just set. Then we perform som actions on the page before quitting the driver.
*/
//create a new Remote driver that will allow your test to send
// commands to the Sauce Labs grid so that Sauce can execute your tests
/** If you're accessing the EU data center, use the following endpoint:.
* https://ondemand.eu-central-1.saucelabs.com/wd/hub
* */
driver = new RemoteWebDriver(new URL("http://ondemand.saucelabs.com:80/wd/hub"), capabilities);
//navigate to the url of the Sauce Labs Sample app
driver.navigate().to("https://www.saucedemo.com");
//Create an instance of a Selenium explicit wait so that we can dynamically wait for an element
WebDriverWait wait = new WebDriverWait(driver, 5);
//wait for the user name field to be visible and store that element into a variable
By userNameFieldLocator = By.cssSelector("[type='text']");
wait.until(ExpectedConditions.visibilityOfElementLocated(userNameFieldLocator));
//type the user name string into the user name field
driver.findElement(userNameFieldLocator).sendKeys("standard_user");
//type the password into the password field
driver.findElement(By.cssSelector("[type='password']")).sendKeys("secret_sauce");
//hit Login button
driver.findElement(By.cssSelector("[type='submit']")).click();
//Synchronize on the next page and make sure it loads
By inventoryPageLocator = By.id("inventory_container");
wait.until(ExpectedConditions.visibilityOfElementLocated(inventoryPageLocator));
/**
* In this section, we confirm the test ran correctly, however we don't post the results to saucelabs.com
*/
//Assert that the inventory page displayed appropriately
Assert.assertTrue(driver.findElement(inventoryPageLocator).isDisplayed());
//Here we tear down the WebDriver session
driver.quit();
}
@Test
public void shouldOpenSafari() throws MalformedURLException {
/**
* In this section, we will configure our SauceLabs credentials in order to run our tests on saucelabs.com
*/
String sauceUserName = "SAUCE_USERNAME";
String sauceAccessKey = "SAUCE_ACCESS_KEY";
/**
* In this section, we will configure our test to run on some specific
* browser/os combination in Sauce Labs
*/
DesiredCapabilities capabilities = new DesiredCapabilities();
//set your user name and access key to run tests in Sauce
capabilities.setCapability("username", sauceUserName);
//set your sauce labs access key
capabilities.setCapability("accessKey", sauceAccessKey);
//set browser to Safari
capabilities.setCapability("browserName", "Safari");
//set operating system to macOS version 10.13
capabilities.setCapability("platform", "macOS 10.13");
//set the browser version to 11.1
capabilities.setCapability("version", "11.1");
//set the build name of the application
capabilities.setCapability("build", "Onboarding Sample App - Java-Junit5");
//set your test case name so that it shows up in Sauce Labs
capabilities.setCapability("name", "1-first-test");
/** If you're accessing the EU data center, use the following endpoint:.
* https://ondemand.eu-central-1.saucelabs.com/wd/hub
* */
driver = new RemoteWebDriver(new URL("https://ondemand.saucelabs.com/wd/hub"), capabilities);
//navigate to the url of the Sauce Labs Sample app
driver.navigate().to("https://www.saucedemo.com");
//Create an instance of a Selenium explicit wait so that we can dynamically wait for an element
WebDriverWait wait = new WebDriverWait(driver, 5);
//wait for the user name field to be visible and store that element into a variable
By userNameFieldLocator = By.cssSelector("[type='text']");
wait.until(ExpectedConditions.visibilityOfElementLocated(userNameFieldLocator));
//type the user name string into the user name field
driver.findElement(userNameFieldLocator).sendKeys("standard_user");
//type the password into the password field
driver.findElement(By.cssSelector("[type='password']")).sendKeys("secret_sauce");
//hit Login button
driver.findElement(By.cssSelector("[type='submit']")).click();
//Synchronize on the next page and make sure it loads
By inventoryPageLocator = By.id("inventory_container");
wait.until(ExpectedConditions.visibilityOfElementLocated(inventoryPageLocator));
//Assert that the inventory page displayed appropriately
Boolean result = driver.findElements(inventoryPageLocator).size() > 0;
assertTrue(result);
/**
* Here we teardown the driver session and send the results to Sauce Labs
*/
if (result){
((JavascriptExecutor)driver).executeScript("sauce:job-result=passed");
}
else {
((JavascriptExecutor)driver).executeScript("sauce:job-result=failed");
}
driver.quit();
}