I need to read alert & confirmation messages displayed in pop ups using java and print it on the console. On export of the selenium recording from the IDE as a Junit4 (WebDriver) java file, my code is:
private WebDriver driver;
private String baseUrl;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
}
Now when I tried to use getAlert or getConfirmation functions as shown:
#Test
public void testSample() throws Exception {
Alert alert = driver.switchTo().alert();
message = alert.getText();
System.out.println("message is "+message);
}
I get the following error:
java.lang.NullPointerException
at com.example.tests.Sample.testSample(Sample.java:40)
at com.example.tests.Sample.main(Sample.java:149)
Exception: null
How do I handle this? Also is there any other way of reading the pop up messages?
In the testSample() method when you navigate to any page by using -
driver.get("URL");
After that can you explain how the alert message comes up in the 1st place.
Are you sure that the pop up message which appears is a javascript alert or any window which is opening up.
If it is a an alert message then you can access it by using -
driver.switchTo().alert();
But if the pop up is another window then you will have to use -
driver.switchTo().window("windowName");
You can get more information about this from here.
Related
io.cucumber.java.PendingException: TODO: implement me
The above error message is displaying while I run my test case.
Browser opened and access the specified URL. After that I'm getting this error.
Can someone help.
#Given("Access the website")
public void access_the_website() throws InterruptedException {
System.setProperty("webdriver.chrome.driver","C://Users//Jayalekshmi//Desktop//Automation//chromedriver.exe");
driver=new ChromeDriver();
driver.manage().window().maximize();
driver.get("URL");
// Write code here that turns the phrase above into concrete actions
System.out.println("heloo");
throw new io.cucumber.java.PendingException();
}
#Given("Click Login option")
public void click_login_option() throws InterruptedException {
driver.wait();
System.out.println("Hiiii");
driver.findElement(By.xpath("/html/body/div[1]/header/div/div/div[2]/div/div/a[1]")).click();
// Write code here that turns the phrase above into concrete actions
throw new io.cucumber.java.PendingException();
My browser opened and window maximized and access the URL.
After that I'm getting error.
After accessing the URL, I'm expecting to click on the Login option available on the website.
Just remove this part:
// Write code here that turns the phrase above into concrete actions
throw new io.cucumber.java.PendingException();
This is added automatically in case you forget to implement the step definition.
getting exception
FAILED CONFIGURATION: #AfterClass tearDown
"org.openqa.selenium.UnsupportedCommandException: The requested resource could not be found, or a request was received using an HTTP method that is not supported by the mapped resource"
enter code here
public class BaseClass {
//read config file and initiate variables
ReadConfig readConfig = new ReadConfig();
public String username = readConfig.getUserName();
//public String password = "asas";
public String password = readConfig.getPassword();
public static AppiumDriver driver;
public static org.apache.logging.log4j.Logger logger;
#BeforeClass
public void setUp ()
{
try {
logger = LogManager.getLogger(BaseClass.class);
DesiredCapabilities dc = new DesiredCapabilities();
dc.setCapability(MobileCapabilityType.DEVICE_NAME, "bd178829");
dc.setCapability(MobileCapabilityType.PLATFORM_NAME, "Android");
dc.setCapability(MobileCapabilityType.APP, "D:\\automation\\CRMNextMobileAutomation\\src\\test\\resources\\apps\\CRMNextNative 6.29.0-release_screenshot_enabled.apk");
dc.setCapability("automationName","UiAutomator2");
dc.setCapability("appPackage", "com.crmnextmobile.crmnextofflineplay");
dc.setCapability("appActivity", "com.crmnextmobile.crmnextofflineplay.qr.QrScannerActivity");
dc.setCapability("enforceAppInsall", true);
URL url = new URL("http://127.0.0.1:4723/wd/hub");
driver = new AppiumDriver(url,dc);
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
System.out.println("CRMNext automation start..");
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
//Clicking on Allow option on open permission pop up
//driver.findElement(By.id("com.android.permissioncontroller:id/permission_allow_button")).click();
if(!driver.findElements(By.id ("com.android.permissioncontroller:id/permission_allow_button")).isEmpty()){
//THEN CLICK ON THE SUBMIT BUTTON
System.out.println("permission_allow_button is found on page");
driver.findElement(By.id("com.android.permissioncontroller:id/permission_allow_button")).click();
}else{
//DO SOMETHING ELSE AS SUBMIT BUTTON IS NOT THERE
System.out.println("permission_allow_button not found on page");
}
//Clicking on Allow button of run in background pop up
//driver.findElement(By.id("android:id/button1")).click();
if(!driver.findElements(By.id ("android:id/button1")).isEmpty()){
//THEN CLICK ON THE SUBMIT BUTTON
System.out.println("button1 is found on page");
driver.findElement(By.id("android:id/button1")).click();
}else{
//DO SOMETHING ELSE AS SUBMIT BUTTON IS NOT THERE
System.out.println("button1 not found on page");
}
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
Thread.sleep(5000);
System.out.println("CRMNext automation Before Skip..");
//Clicking on Skip button
driver.findElement(By.id("com.crmnextmobile.crmnextofflineplay:id/skip")).click();
System.out.println("CRMNext automation after Skip..");
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
Thread.sleep(10000);
driver.findElement(By.id("com.crmnextmobile.crmnextofflineplay:id/relative_layout_continue")).click();
Thread.sleep(2000);
} catch (Exception exp) {
// TODO: handle exception
System.out.println("Cause is :"+exp.getCause());
System.out.println("Message is :"+exp.getMessage());
exp.printStackTrace();
}
}
#Test
public void sample() {
System.out.println("Sample run");
}
#AfterClass
public void tearDown()
{
driver.close();
driver.quit();
}
//org.openqa.selenium.UnsupportedCommandException: The requested resource could not be found, or a request was received using an HTTP method that is not supported by the mapped resource
all tests are failing due to this.
driver.close()
The driver.close() command is used to close the current browser window having focus. In case there is only one browser open then calling driver.close() quits the whole browser session.
Usability
Use driver.close() when dealing with multiple browser tabs or windows e.g. when clicking on a link that opens another tab. In this case after performing required action in the new tab, to close the tab, call the driver.close() method.
driver.quit()
The driver.quit() is used to quit the whole browser session along with all the associated browser windows, tabs and pop-ups.
Usability
Use driver.quit() when no longer want to interact with the driver object along with any associated window, tab or pop-up. Generally, it is the last statements of the automation scripts. Call driver.quit() in the #AfterClass method to close it at the end of the whole suite.
Use following code in #AfterClass
#AfterClass
public void tearDown()
{
if (driver != null)
driver.Quit();
}
I want to get text of pop up using selenium webdriver.
Open URL https://ads.google.com/intl/en_IN/home/pricing/
Click on link 1800-419-6346* ( I am having xpath for this driver.findElement(By.xpath("//a[#class='eto eto-number']")).click();)
Now after click on above link , Here one Pop up is getting displayed which is showing message as “Open FaceTime?” .
How we can handle such type of pop up , I just know “Open FaceTime” is application which run on MacBook .
I tried to handle with alert class but it did not work.
Alert alert=driver.switchTo().alert();
System.out.println(alert.getText());
after running code ,I am getting message "no such alert"
Please note on Windows machine that popup will not be displayed, it is specific to Macbook.
My Code as below :-
public class Session1Mac {
WebDriver driver;
#BeforeMethod
public void setUp() throws InterruptedException{
System.out.println("enter into first method");
System.setProperty("webdriver.chrome.driver", "/Users/aturkar/eclipse-workspace/AutomateBSQATaskonMac/Lib/chromedriver");
driver = new ChromeDriver(); // launch chrome
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get("https:/ads.google.com/intl/en_IN/home/pricing/");
Thread.sleep(20);
}
#Test()
public void VerifyRedirectingToDialer() throws InterruptedException, Exception{
// driver.findElement(By.linkText("800-419-6346*")).click();
driver.findElement(By.xpath("//a[#class='eto eto-number']")).click();
Thread.sleep(5000);
System.out.println("Element got clicked");
Alert alert=driver.switchTo().alert();
System.out.println(alert.getText());
}
}
Error on Console:-
Actual:-
org.openqa.selenium.NoAlertPresentException: no such alert
Expected:-I Want to get text of "Pop-up", if yes then how we can get it ? could you please help me with this.
driver.findElement(By.xpath(OR.getProperty(object))).click();
System.out.println("Test");
Click works for some button.But on clicking a specific button in application.
But 'org.openqa.selenium.remote.SessionNotFoundException' erro comes after the above driver action. Test is not printed on console after that click. Why is it so?
public static void click(String object, String data){
try{
/*try
{
driver.switchTo().alert().accept();
}
catch(Exception e){}*/
new WebDriverWait(driver, 30).until(ExpectedConditions.elementToBeClickable(By.xpath(OR.getProperty(object))));
driver.findElement(By.xpath(OR.getProperty(object))).click();
System.out.println("Test");
Log.info("Clicking on Webelement "+ object);
}catch(Exception e){
Log.error("Not able to click --- " + e.getMessage());
DriverScript.bResult = false;
}
}
This is the code. Its a keyword driven framework. This action keyword gets executed 6 times perfectly. But on clicking some button which popups new window this error occurs. Switch window is supposed to be the next action keyword to be executed. But it is not reaching there . Just after .click it stands idle for long time. Then the above exception.
public static void switchwindow(String object,String data){
try{
parentHandle = driver.getWindowHandle();
System.out.println(driver.getWindowHandles().size());// get the current window handle
for (String winHandle : driver.getWindowHandles()) {
if(winHandle.equalsIgnoreCase("73e19507-bf40-44ce-822a-62630be49c2b"))
{driver.switchTo().window(winHandle);break;} // switch focus of WebDriver to the next found window handle (that's your newly opened window)
}
Log.info("Switched to new window");
}
catch(Exception e){
Log.error("Not able to switch the window --- " + e.getMessage());
DriverScript.bResult = false;
}
}
Seems that your browser is already closed.
I would simplified tests and not call quit anywhere in code.
I would also tried if problem exist in other browsers. Also U could debug or introduce sleeps to check where execly problem is.
I suspect there could be an issue with your code for switching windows. It would be better to debug if you could show the code for switching windows.
I am testing a web App which contains phone/voice verification in one process flow, I am trying to automate this verification process. My Query is:
Is there any way to do it manually like for example entering phone(text)/voice code manually when occurs, while enter code the thread sleeps or wait 'until ExpectedConditon'?
For example: we'll do in the case when the page is in processing phase so, we use
wait.until(ExpectedConditions.presenceOfElementLocated(By.some selector));
it will wait for certain 'timeOutSeconds'.
thanks in advance..........
This is a simple example that i wrote that i'll think it's going to suit your need. In this code the driver starts opening Google. Once the page fully loads the console waits for the input data on the console (i.e. http://www.stackoverflow.com).
This code will probably solve your issue with the manual input during test run.
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
InputStreamReader istream = new InputStreamReader(System.in);
BufferedReader bufRead = new BufferedReader(istream);
String nextWebSite = "http://www.google.com";
driver.get(nextWebSite);
try {
System.out.println("What's the next Website you'll like to visit? ");
nextWebSite = bufRead.readLine();
} catch (IOException err) {
System.out.println("Sorry, there was a problem reading the informed data");
}
driver.get(nextWebSite);
driver.close();
driver.quit();
}