using Java 17 and slenium 4.0
wait.until(ExpectedConditions.titleContains("BrowserStack"));
here is full code :
public class mainTestClass {
public static final String USERNAME = "myuser *****";
public static final String AUTOMATE_KEY = "my ke *****";
public static final String URL = "https://" + USERNAME + ":" + AUTOMATE_KEY + "#hub-cloud.browserstack.com/wd/hub";
public static void main(String[] args) throws Exception {
Thread object1 = new Thread(new TestClass1());
object1.start();
Thread object2 = new Thread(new TestClass2());
object2.start();
Thread object3 = new Thread(new TestClass3());
object3.start();
}
public void executeTest(Hashtable<String, String> capsHashtable) {
String key;
DesiredCapabilities caps = new DesiredCapabilities();
// Iterate over the hashtable and set the capabilities
Set<String> keys = capsHashtable.keySet();
Iterator<String> itr = keys.iterator();
while (itr.hasNext()) {
key = itr.next();
caps.setCapability(key, capsHashtable.get(key));
}
WebDriver driver;
try {
driver = new RemoteWebDriver(new URL(URL), caps);
JavascriptExecutor jse = (JavascriptExecutor)driver;
// Searching for 'BrowserStack' on google.com
driver.get("https://www.google.com");
WebElement element = driver.findElement(By.name("q"));
element.sendKeys("BrowserStack");
element.submit();
// Setting the status of test as 'passed' or 'failed' based on the condition; if title of the web page contains 'BrowserStack'
WebDriverWait wait = new WebDriverWait(driver, 5);
try {
// wait.until(ExpectedConditions.titleContains("BrowserStack"));
jse.executeScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\": \"passed\", \"reason\": \"Title matched!\"}}");
}
catch(Exception e) {
jse.executeScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\":\"failed\", \"reason\": \"Title not matched\"}}");
}
System.out.println(driver.getTitle());
driver.quit();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
This is cause in Selenium 4.0.0 (Stable)
WebDriverWait which takes driver and timeoutInSeconds long, have been Deprecated
#Deprecated
public WebDriverWait(WebDriver driver, long timeoutInSeconds) {
this(driver, Duration.ofSeconds(timeoutInSeconds));
}
Fix:
Selenium devs have given this method instead
public WebDriverWait(WebDriver driver, Duration timeout) {
this(
driver,
timeout,
Duration.ofMillis(DEFAULT_SLEEP_TIMEOUT),
Clock.systemDefaultZone(),
Sleeper.SYSTEM_SLEEPER);
}
so your effective code will be :
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
try {
wait.until(ExpectedConditions.titleContains("BrowserStack"));
JavascriptExecutor jse = (JavascriptExecutor)driver;
}
catch(Exception e) {
e.printStackTrace();
}
Related
I'm new to Selenium & new to Java as well. So maybe I'm missing something obvious, but I’m spinning on this for a while now, can't move forward & totally desperate. Please help!
Here is my set-up:
My custom Driver class implements WebDriver & sets property:
public class Driver implements WebDriver {
private WebDriver driver;
private String browserName;
public Driver(String browserName) throws Exception {
this.browserName = browserName;
if(browserName.equalsIgnoreCase("chrome")) {
System.setProperty("webdriver.chrome.driver", "src/test/resources/chromedriver");
this.driver = new ChromeDriver();
}
else if(browserName.equalsIgnoreCase("firefox")) {
System.setProperty("webdriver.gecko.driver", "src/test/resources/geckodriver");
this.driver = new FirefoxDriver();
}
else {
throw new Exception("Browser is not correct");
}
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
<...>
}
BaseTest class gets property & creates new instance of the Driver inside #BeforeClass method (browser name passed with a maven command when running the test):
String browserName = getParamater("browser");
driver = new Driver(browserName);
In the Test class inside the #Test I create new Actions & pass there the driver from BaseTest:
Actions builder = new Actions(driver);
Action mouseOverHome = builder
.moveToElement(pb.testGoodle)
.build();
mouseOverHome.perform();
And this code doesn’t work -> no Actions performed (no mouse over or anything), no errors too.
However if I create & define new WebDriver inside the #Test itself:
System.setProperty("webdriver.gecko.driver", "src/test/resources/geckodriver");
WebDriver driver = new FirefoxDriver();
Actions perfectly working.
Any ideas or hints very appreciated!
Resolved! Resolved! The problem was in messed Actions declaration in Page Object! Here how things look in the Page Object:
protected Driver driver;
public static Actions act;
public PlanBuilder(Driver driver) {
this.driver = driver;
PageFactory.initElements(driver, this);
this.act = new Actions(driver);
}
public void rightClick (WebElement element) throws InterruptedException {
// Actions builder = new Actions(basedriver);
Action openContextMenu = driver.act
.contextClick(element)
.build();
openContextMenu.perform();
Thread.sleep(4000);
}
public class BasePage
{
public static IWebDriver driver;
public static JObject jobject;
public static JArray jarray;
public static void SeleniumInit()
{
BasePage.ReadJsonObject("InitData.json");
string browser = jobject.SelectToken("browser").Value<string>();
string Headless = jobject.SelectToken("Headless").Value<string>();
if (browser == "Chrome")
{
ChromeOptions options = new ChromeOptions();
options.AddArguments("-start-maximized");
if (Headless == "True")
{
options.AddArguments("-headless");
}
driver = new ChromeDriver(options);
}
else if (browser == "Firefox")
{
FirefoxOptions options = new FirefoxOptions();
options.AddArguments("-start-maximized");
if (Headless == "True")
{
options.AddArguments("-headless");
}
driver = new FirefoxDriver(options);
}
else
{
EdgeOptions options = new EdgeOptions();
options.AddArguments("-start-maximized");
if (Headless == "True")
{
options.AddArguments("-headless");
}
driver = new EdgeDriver(options);
}
}
public static void Write(By by, string user)
{
try
{
driver.FindElement(by).SendKeys(user);
TakeScreenshot(Status.Pass, "Write " + user);
}
catch (Exception ex)
{
TakeScreenshot(Status.Fail, "Write Failed: " + ex.ToString());
Assert.Fail();
}
}
public static void Click(By by)
{
try
{
driver.FindElement(by).Click();
TakeScreenshot(Status.Pass, "Click");
}
catch (Exception ex)
{
TakeScreenshot(Status.Fail, "Click Failed: " + ex.ToString());
Assert.Fail();
}
}
public static void OpenUrl(string url)
{
try
{
driver.Url = url;
TakeScreenshot(Status.Pass, "Open url: " + url);
}
catch (Exception ex)
{
TakeScreenshot(Status.Fail, "Open Url Failed: " + ex.ToString());
Assert.Fail();
}
}
public static void Clear(By by)
{
try
{
driver.FindElement(by).Clear();
TakeScreenshot(Status.Pass, "Clear Text: " );
}
catch (Exception ex)
{
TakeScreenshot(Status.Fail, "Clear Text Failed: " + ex.ToString());
Assert.Fail();
}
}
public static void ClickRadio(By by)
{
try
{
Actions actions = new Actions(driver);
IWebElement radioLocator = driver.FindElement(by);
actions.Click(radioLocator).Build().Perform();
TakeScreenshot(Status.Pass, "Click Radio Button");
}
catch (Exception ex)
{
TakeScreenshot(Status.Fail, "Radio Button Click Failed: " + ex.ToString());
Assert.Fail();
}
}
public static void SelectOption(By by, string value)
{
try
{
var dropdown = driver.FindElement(by);
var selectDropdown = new SelectElement(dropdown);
selectDropdown.SelectByValue(value);
TakeScreenshot(Status.Pass, "Select Option from Dropdown Menu");
}
catch (Exception ex)
{
TakeScreenshot(Status.Fail, "Select Option Failed: " + ex.ToString());
Assert.Fail();
}
}
public static string GetElementText(By by)
{
string text;
try
{
text = driver.FindElement(by).Text;
}
catch
{
try
{
text = driver.FindElement(by).GetAttribute("value");
}
catch
{
text = driver.FindElement(by).GetAttribute("innerHTML");
}
}
return text;
}
public static void Assertion(By by, string assertText)
{
try {
string Text = GetElementText(by);
Assert.AreEqual(assertText, Text);
TakeScreenshot(Status.Pass, "Assertion Passed");
}
catch (Exception ex)
{
TakeScreenshot(Status.Fail, "Assertion Failed: " + ex.ToString());
Assert.Fail();
}
}
public static void sleep()
{
Thread.Sleep(10000);
}
public static string GetElementState(By by)
{
string elementState = driver.FindElement(by).GetAttribute("Disabled");
if (elementState == null)
{
elementState = "enabled";
}
else if (elementState == "true")
{
elementState = "disabled";
}
return elementState;
}
public static void ExplicitWait(By by)
{
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(60));
wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(by));
//wait.Until(Driver => IsPageReady(Driver) == true && IsElementVisible(by) == true && IsClickable(by) == true);
//wait.IgnoreExceptionTypes(typeof(NoSuchElementException));
//wait.Until(driver => IsElementVisible(driver, By.Id("username")) == true);
}
public static void ImplicitWait()
{
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(60);
}
public static void FluentWait()
{
DefaultWait<IWebDriver> fluentWait = new DefaultWait<IWebDriver>(driver);
fluentWait.Timeout = TimeSpan.FromSeconds(60);
fluentWait.PollingInterval = TimeSpan.FromMilliseconds(250);
/* Ignore the exception - NoSuchElementException that indicates that the element is not present */
fluentWait.IgnoreExceptionTypes(typeof(NoSuchElementException));
fluentWait.Message = "Element to be searched not found";
}
public static void scrollDown()
{
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
js.ExecuteScript("window.scrollTo(0, document." + "Body" + ".scrollHeight);");
}
public static void switchWindow()
{
driver.SwitchTo().Window(driver.WindowHandles[1]);
}
public static void TakeScreenshot(Status status, string stepDetail)
{
string path = #"C:\ExtentReports\" + "TestExecLog_" + DateTime.Now.ToString("yyyyMMddHHmmss");
Screenshot image = ((ITakesScreenshot)driver).GetScreenshot();
image.SaveAsFile(path + ".png", ScreenshotImageFormat.Png);
ExtentReport.exChildTest.Log(status, stepDetail, MediaEntityBuilder.CreateScreenCaptureFromPath(path + ".png").Build());
}
public static void ReadJson(string filename)
{
string myJsonString = File.ReadAllText(#"..\\..\\..\\" + filename);
jarray = JArray.Parse(myJsonString);
}
public static void ReadJsonObject(string filename)
{
string myJsonString = File.ReadAllText(#"..\\..\\..\\" + filename);
jobject = JObject.Parse(myJsonString);
}
}
How should I use sendKeys in loop? First time sendKeys work correct, but second time, on the new page - exception.
public class main {
public static void main(String args[]) throws Exception{
System.setProperty("webdriver.gecko.driver", "C:\\Users\\asdasd\\Desktop\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://www.kommersant.ru");
Scanner scanner = new Scanner(System.in);
while(true) {
WebElement search = driver.findElement(By.cssSelector(".search__input"));
// WebElement searchButton = driver.findElement(By.cssSelector(".search__button"));
String s = scanner.nextLine();
if(s.equals("exit")){
break;
}
else {
WebDriverWait wait = new WebDriverWait(driver, 10);
search.sendKeys(s);
WebElement searchButton = wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector(".search__button")));
searchButton.click();
searchButton.click();
}
}
driver.quit();
}
}
Try to get your loop condition right.The problem lies there.
I'm trying to type selenium in google and get all the title text of result in a notepad file. i want to get all available links on all the pages, till last page of search. but only 1st page's link i am getting. when i debug and run, it is working for some 10 pages.help me in this.
JAVA code:
public class weblink
{
public static void main(String[] args) throws IOException, InterruptedException {
WebDriver driver;
System.setProperty("webdriver.chrome.driver", "E:\\disha.shah/myWork/eclipse/chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://www.google.co.in/");
driver.findElement(By.id("lst-ib")).sendKeys("Selenium");
driver.findElement(By.id("_fZl")).click();
PrintStream ps = new PrintStream(new File(("E:\\disha1.txt")));
do
{
List<WebElement> findElements = driver.findElements(By.xpath("//*[#id='rso']//h3/a"));
for (WebElement webElement : findElements)
{
System.out.println("-" + webElement.getText()); // for title
//System.out.println(webElement.getAttribute("href")); // for links
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
System.setOut(ps);
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
}
Thread.sleep(1000);
if(driver.findElement(By.linkText("Next")).isDisplayed()== true)
{
driver.findElement(By.linkText("Next")).click();
}
else
{
System.out.println("All Link is Covered");
}
}
while(driver.findElement(By.linkText("Next")).isDisplayed() );
{
//Thread.sleep(2000);
}
}
}
I've done some correction. the updated code is below.-
public static void main(String[] args) throws IOException, InterruptedException
{
WebDriver driver;
System.setProperty("webdriver.chrome.driver", "D:/Application/chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get("http://www.google.co.in/");
driver.findElement(By.id("lst-ib")).sendKeys("Selenium");
driver.findElement(By.id("_fZl")).click();
Boolean nextButtonFlag = true;
// Create two separate file storing the result
PrintStream searchTitle = new PrintStream(new File(("D:\\Titles.txt")));
PrintStream searchLink = new PrintStream(new File(("D:\\Links.txt")));
do
{
List<WebElement> findElements = driver.findElements(By.xpath("//h3[#class='r']/a"));
for (WebElement element : findElements)
{
// Write all received links and title inn txt file
searchTitle.append(element.getText()+"\n");
searchLink.append(element.getAttribute("href")+"\n");
}
Thread.sleep(2000);
try
{
driver.findElement(By.linkText("Next")).click();
}
catch(Exception e)
{
// no more next button to navigate further link
nextButtonFlag=false;
}
Thread.sleep(2500);
}
while(nextButtonFlag);
System.out.println("Execution done");
searchTitle.close();
searchLink.close();
}
}
Class1:
public class LaunchApp {
AndroidDriver<WebElement> driver;
#BeforeTest
public void Test1() throws MalformedURLException {
DesiredCapabilities capability = new DesiredCapabilities();
capability.setCapability("deviceName", "Android");
capability.setCapability("platformName", "Android");
capability.setCapability("platformVersion", "5.1.1");
capability.setCapability("deviceName", "Samsung Galaxy On5");
capability.setCapability("app",
"D:\\whatsapp.apk");
capability.setCapability("PackageName",
"com.movocado.socialbostonsports");
capability.setCapability("ActivityName",
"com.movocado.socialbostonsports.Activity.LogInSceen");
try {
driver = new AndroidDriver<WebElement>(new URL(
"http://127.0.0.1:4723/wd/hub"), capability);
} catch (MalformedURLException e) {
e.printStackTrace();
}
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
Class2:
public class DrawerMenuTest {
AndroidDriver<WebElement> driver;
#Test(priority = 1)
public void DrawerMenuIcon() {
WebElement drawerMenu = driver.findElement(By
.id("com.movocado.socialbostonsports:id/rel_drawer"));
try {
drawerMenu.click();
} catch (NullPointerException e) {
System.out.println(e.getMessage());
}
}
Problem:
Second class is showing NullPointerException. Suggest me a solution.
You are initializing AndroidDriver into LaunchApp but does not pass this driver reference into DrawerMenuTest where you are creating only refrence variable of AndroidDriver with null that's causes of NullPointerException.
To overcome it you should create separate singlton class which will give single instance of AndroidDriver to each and every class as below :-
public class DriverInit {
private AndroidDriver<WebElement> driver;
private static DriverInit driverInit = null;
public static DriverInit getInstance() {
if (driverInit == null) {
driverInit = new DriverInit();
}
return driverInit;
}
private DriverInit() {
DesiredCapabilities capability = new DesiredCapabilities();
capability.setCapability("deviceName", "Android");
capability.setCapability("platformName", "Android");
capability.setCapability("platformVersion", "5.1.1");
capability.setCapability("deviceName", "Samsung Galaxy On5");
capability.setCapability("app", "D:\\whatsapp.apk");
capability.setCapability("PackageName", "com.movocado.socialbostonsports");
capability.setCapability("ActivityName", "com.movocado.socialbostonsports.Activity.LogInSceen");
this.driver = new AndroidDriver<WebElement>(new URL(
"http://127.0.0.1:4723/wd/hub"), capability);
this.driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
public WebDriver getDriver() {
return this.driver;
}
}
Now you can use this into LaunchApp class as below :-
public class LaunchApp {
AndroidDriver<WebElement> driver;
#BeforeTest
public void Test1() throws MalformedURLException {
driver = DriverInit.getInstance().getDriver();
//now do your stuff with this driver
}
}
And use in DrawerMenuTest class as below :-
public class DrawerMenuTest {
AndroidDriver<WebElement> driver;
#Test(priority = 1)
public void DrawerMenuIcon() {
//get driver instance first
driver = DriverInit.getInstance().getDriver();
WebElement drawerMenu = driver.findElement(By
.id("com.movocado.socialbostonsports:id/rel_drawer"));
try {
drawerMenu.click();
} catch (NullPointerException e) {
System.out.println(e.getMessage());
}
}
}
Hope it helps..:)
Complete code is written to fetch data from excel and login to Gmail, but while trying to do so my browser had opened and also the desired page got opened and as well as login id was picked from excel and stored in the variable sUsername, but unable to locate the xpath as- element=driver.findElement(by.id("Email")); but when I print element it holds "null", where as expected was some address of the locator id. Further by using the address of id I would had used with sendkeys to enter the email address in the text box.
But the following error was displayed:
java.lang.NullPointerException
at appModules.SignIN.Execute(SignIN.java:21)
Login class-where the locator issue exists: at - Login1.userName(driver).sendKeys(sUsername);
public class Login1 {
//private static WebDriver driver=null;
private static WebElement element=null;
public static WebElement userName(WebDriver driver)
{
try {
System.out.println("aaa");
System.out.println("bb");
element=driver.findElement(By.name("Email"));
System.out.println("ccc");
} catch (Exception e) {
// TODO: handle exception
System.out.println(element);
}
return element;
}
public static WebElement btn_login(WebDriver driver)
{
element= driver.findElement(By.id("next"));
return element;
}
public static WebElement passWord(WebDriver driver)
{
element= driver.findElement(By.id("Passwd"));
return element;
}
public static WebElement btn_SignIN(WebDriver driver)
{
element= driver.findElement(By.id("signIn"));
return element;
}
}
This is the SigniN class where iam getting the java null pointer exception--issue exists: at- Login1.userName(driver).sendKeys(sUsername);
public class SignIN {
private static WebDriver driver=null;
public static void Execute (int iTestCaseRow)
{
String sUsername=ExcelUtils1.getCellData(iTestCaseRow,Constant1.col_UserName);
System.out.println(sUsername);
//driver.ma3nage().window().maximize();
//driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
Login1.userName(driver).sendKeys(sUsername);
//driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
Login1.btn_login(driver).click();
String pass=ExcelUtils1.getCellData(iTestCaseRow, Constant1.col_password1);
Login1.passWord(driver).sendKeys(pass);
Login1.btn_SignIN(driver).click();
}
}
This is where I have instantiate the browser--
public class Utils1 {
public static WebDriver driver;
public static WebDriver OpenBrowser(int iTestCaseRow) {
String sBrowserName;
System.out.println(iTestCaseRow);
sBrowserName = ExcelUtils1.getCellData(iTestCaseRow,
Constant1.col_browser);
if (sBrowserName.equals("Mozilla")) {
driver = new FirefoxDriver();
// Log.info("New driver instantiated");
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
// Log.info("Implicit wait applied on the driver for 10 seconds");
driver.get(Constant1.URL);
// Log.info("Web application launched successfully");
}
return driver;
}
}
It is good practice to deal with internally as well explicit wait for locating element. If there is page related activity then also need to use wait for page to load.
Please follow bellow code
For internal Wait
protected WebElement waitForPresent(final String locator) {
// timeout is your default wait timeout in long.
return waitForPresent(locator, timeout);
}
For Explicit Wait
protected WebElement waitForPresent(final String locator, long timeout) {
WebDriverWait wait = new WebDriverWait(driver, timeout);
WebElement ele = null;
try {
ele = wait.until(ExpectedConditions
.presenceOfElementLocated(locator));
} catch (Exception e) {
throw e;
}
return ele;
}
protected WebElement waitForNotPresent(final String locator, long timeout) {
timeout = timeout * 1000;
long startTime = System.currentTimeMillis();
WebElement ele = null;
while ((System.currentTimeMillis() - startTime) < timeout) {
try {
ele = findElement(locator);
Thread.sleep(1000);
} catch (Exception e) {
break;
}
}
return ele;
}
Just spit balling here, but in addition to the copy/paste issues stated above.. I don't see where you do a 'get' to load the gmail page for the driver instance you are creating? Something like..
driver.get("https://mail.google.com/something");
Also, it would probably be a good idea to put an explicit wait in place for the "Email" field before doing the findElement as the page may still be rendering:
Wait<WebDriver> doFluentWait = fluentWait = new FluentWait<>(driver).withTimeout(PAGE_LOAD_WAIT, TimeUnit.SECONDS)
.pollingEvery(POLLING_INTERVAL, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);
and then do something like
doFluentWait.until(WebDriverUtil.elementIsVisible(By.name("Email")));