How to Handle the Alert Pop Up - java

I am working on the Web Application, In that Application user need to send the values into
the Search Text Box, then user need to click on the Search Button, If the Value are
avilable in the db, then that value will be display on the another Text Box, If that value
in not in the db, Then Alert Pop up is Displaying on the screen, At that i am using below
code, But it is not working fine.
if(driver.findElement(By.id(APL.MT_ET_Search_Btn_ID)).isEnabled())
{
driver.findElement(By.id(APL.MT_ET_Search_Btn_ID)).click();
System.out.println("Clicked on the Search Button for the Text box");
Thread.sleep(2000);
//Handling the Code
String page = driver.getTitle();
System.out.println(page);
if(page.equals("No Recipients found"));
{
System.out.println("No Recipients found");
driver.switchTo().alert().accept();
System.out.println("Handling the Pop Up");
}
}

You have an error in the second if, remove the semicolon and it will be better.
if(driver.findElement(By.id(APL.MT_ET_Search_Btn_ID)).isEnabled())
{
driver.findElement(By.id(APL.MT_ET_Search_Btn_ID)).click();
System.out.println("Clicked on the Search Button for the Text box");
Thread.sleep(2000);
//Handling the Code
String page = driver.getTitle();
System.out.println(page);
if(page.equals("No Recipients found")) //#############HERE
{
System.out.println("No Recipients found");
driver.switchTo().alert().accept();
System.out.println("Handling the Pop Up");
}
}
Anyway if you please tell us WHY is not working I can check if there can be other problems.

Related

Same logic should Continue with alert web element for invalid user id & password and it should skip that alert web element for positive test cases

My login page is similar to google login page. If the user id is correct then password text box is enable and if it incorrect user id it will show error message and password text box is disabled.
I am trying to do automation testing. For Invalid user id compare the error message and closing the browser. and valid user id it should enter the password and login successfull.
For the below code negative flow is working fine but positive flow it get stuck in the alert webelement and it is not moving further.
WebElement message = driver.findElement(By.xpath("//div[#class='MuiAlert-message']"));
How to I skip the above code to continue my positive flow.
4) I have used try{}catch{}, isempty(),size(), wait, thread.sleep(), control reading the web element but not moving further for positive flow. Showing timeout exception, no such sessionexception error.
Here is the below code of login page.
if(driver.findElement(By.name("email")).isEnabled())
{
WebElement userid= driver.findElement(By.name("email")); // user id for login page
userid.clear();
userid.sendKeys(user);
WebElement Button = driver.findElement(By.xpath("//span[#class='MuiButton-label']")); // continue to get password text box
Button.click();
System.out.println("entering login page");
String expected = "Email is not registered with xxx";
WebElement message = driver.findElement(By.xpath("//div[#class='MuiAlert-message']"));
String text= message.getText();
System.out.println(text);
if (message.isEnabled() && text.contains(expected))
{
Assert.assertTrue(true);
System.out.println("closing the browser");
driver.close();
}else
{
System.out.println("Entering password page");
WebElement password= driver.findElement(By.name("password"));
password.clear();
password.sendKeys(pwd);
WebElement loginbutton= driver.findElement(By.xpath("//span[normalize-space()='Login with password']"));
loginbutton.click();
System.out.println(" title is getting entered ");
String exp_title1 = "xxxx" ;
String exp_title2 = "xxx";
String actual_title =driver.getTitle();
System.out.println(actual_title);
//Thread.sleep(1000);
if(exp.equals("PASS"))
{
if((exp_title1.equals(actual_title)) || (exp_title2.equals(actual_title)))
{
driver.findElement(By.xpath("//h6[#class='MuiTypography-root MuiTypography-subtitle1 MuiTypography-colorPrimary']")).click();
driver.findElement(By.xpath("//li[2]")).click();
driver.findElement(By.name("logout")).click();
driver.findElement(By.id("proceed-button")).click();
Assert.assertTrue(true);
}
else
{
Assert.assertTrue(false);
// driver.close();
}
}
}
}

In Java, one of my alert boxes is showing twice and the nested alert box is not showing at all

I am working on a school project where I am working with a mySQL database. The specific part I'm working on right now is what happens when a user of the system attempts to delete an appointment from the database. I have three alerts, one works, one is presenting twice, and the other isn't working at all. The first loop, the one that verifies a choice is selected does work. The second one that confirms if the user wants to delete runs twice, i.e. when you click the OK button it shows again and you must click again. Then, it seems to skip to the bottom where I reload the page. When it reloads the page I can see that the appointment was successfully deleted and it also shows as deleted in the mysql work bench. So it's only the middle alert that doesn't seem to run at all. I have scoured the internet to find out why one is showing twice and the other not at all and although I have found similar questions and problems I tried using their solutions and I did not see any difference. I appreciate any help in the right direction be it code correction or resources! Thank you very much in advance.
// delete selected appointment
#FXML
void handleDelete(MouseEvent event) throws IOException, SQLException {
Appointment ifSelected = appointmentTable.getSelectionModel().getSelectedItem();
if (ifSelected == null){
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("Deletion Error");
alert.setHeaderText("You didn't choose an appointment to delete.");
alert.setContentText("Please click ok in order to choose an appointment for deletion.");
alert.showAndWait();
}
else{
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setTitle("Appointment Deletion");
alert.setHeaderText("You are about to delete an appointment record permanantly.");
alert.setContentText("If you want to proceed, click ok.");
Optional<ButtonType> result = alert.showAndWait();
if (result.isPresent() && result.get() == ButtonType.OK){
Alert alert2 = new Alert(Alert.AlertType.INFORMATION);
alert2.setTitle("Deletion Successful");
alert2.setHeaderText("You successfully deleted the appointment with " + ifSelected.getCustomerName()+ " at " + ifSelected.getStartTime() + ".");
alert.setContentText("If you want to proceed, click ok.");
alert.show();
Statement stmt = conn.createStatement();
apptID = ifSelected.getAppointmentID();
String sqlDeleteAppointment = "DELETE FROM appointment WHERE appointmentId = " + apptID;
Query.makeQuery(sqlDeleteAppointment);
Parent root = FXMLLoader.load(getClass().getResource("appointmentScreen.fxml"));
scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
}}
'''
You have created alert2 object from Alert class for your nested Alerts. But you have used alert object instead of alert2.
Alert alert2 = new Alert(Alert.AlertType.INFORMATION);
alert2.setTitle("Deletion Successful");
alert2.setHeaderText("You successfully deleted the appointment with " + ifSelected.getCustomerName()+ " at " + ifSelected.getStartTime() + ".");
alert2.setContentText("If you want to proceed, click ok.");
alert2.show();

WebElement Comparison

In my project, I have several datas with checkboxes if I click those different set of data and try to delete that I am getting two types of alerts: one is "deleted successfully" for one data and for other data it showing "data cannot be deleted" popup. How to handle these both in Selenium?
I used if-else statement compared both webelement string using getText() method but it is showing NoSuchElementException.
Here is my code:
WebElement Popup = driver.findElement(By.Xpath="//input[#class='btn-btn-popup']")
WebElement e = driver.findElement(By.xpath="//div[#text='Deleted successfully']");
String Deletepopup = e.getText();
WebElement f = driver.findElement(By.xpath="//div[#text='Data Cannot be deleted']");
String CannotDeltedPopup = f.getText();
if (Deletepopup.equals("Deleted Successfully")) {
Popup.click();
}
else if (CannotDeletedPopup.equals("Data Cannot be deleted")) {
Popup.click();
}
Of course you get NoSuchElementException. You try to find both WebElements, but you can have present only one at a time.
If your action succeed you will have present this
driver.findElement(By.xpath("//div[#text='Deleted successfully']")) and this driver.findElement(By.xpath("//div[#text='Data Cannot be deleted']")) will throw NoSuchElementException and vice versa for action failed.
In your case I recommend you to use try-catch block.
String txt;
try{
txt = driver.findElement(By.xpath("//div[#text='Deleted successfully']")).getText();
}catch(NoSuchElementException e){
try{
txt = driver.findElement(By.xpath("//div[#text='Data Cannot be deleted']")).getText();
}catch(NoSuchElementException e1){
txt = "None of messages was found"; //this will happend when none of elements are present.
}
}
I this case you will try to find message 'Deleted successfully' and if it is not present will try to find message 'Data Cannot be deleted'.
Also I will recommend you to use Explicit Wait, to give your app some time to look for you element before to throw NoSuchElementException.
String txt;
try{
WebDriverWait wait=new WebDriverWait(driver, 10);
txt = wait.until(ExpectedConditions.visibilityOfElementLocated(
By.xpath("//div[#text='Deleted successfully']"))
).getText();
}catch(NoSuchElementException e){
try{
WebDriverWait wait=new WebDriverWait(driver, 10);
txt = wait.until(ExpectedConditions.visibilityOfElementLocated(
By.xpath("//div[#text='Data Cannot be deleted']"))
).getText();
}catch(NoSuchElementException e1){
txt = "None of messages was found"; //this will happend when none of elements are present.
}
}
This will give 10 seconds time to look for element before to throw NoSuchElementException. You can change this time to how much do you need to increase success of your app.

Selenium check if a window is currently open

So I have a selenium webdriver logging me into a website and from there I click a button which opens a second window. I use this code below to switch to the new window
String winParent = driver.getWindowHandle();
for (String winHandle : driver.getWindowHandles()) {
driver.switchTo().window(winHandle);
}
Now on that second window I run some automation . Once complete I would press the save button and this would close the current window. If the window doesn't close it means I have some errors on the page and I need to loop back and fix it.
driver.findElement(By.id("btnSave")).click();
if (isAlive(driver) == false) {
//break and exit
System.out.println("cic" + name);
finalString = finalString + "cic: " + name;
break;
}
public Boolean isAlive(WebDriver driver) {
try {
driver.getCurrentUrl();//or driver.getTitle();
return true;
} catch (Exception ex) {
return false;
}
}
The The program works as expected when it catches the errors and the window doesn't close. But as soon as everything is clear and the window closes it enters the if statement above and displays this error.
Unable to receive message from renderer.
I believe that I'm not checking if the window has been closed correctly.
edit: after some debugging it seems like once the window closes the program can't really tell what to do next. http://i.imgur.com/l8nsPPr.png
I suggest using windowHandle for this.
You are saving initial window in String winParent = driver.getWindowHandle();
Then you switch to the second window, which will have different handle.
When you need to check if the second window is still open, just use:
private boolean isNewWindowOpened(WebDriver driver, String parentWindowHandle) {
try {
return !driver.getWindowHandle().equals(parentWindowHandle);
} catch (Exception ex) {
driver.switchTo(parentWindowHandle);
return false;
}
I came across the same situation, I've got a solution for you, check window count after clicking on "Save" button. Ideally, there will be one window if you have provided all the correct data and if not then there are two windows.
driver.findElement(By.id("btnSave")).click();
if (driver.getWindowHandled().size() >= 2) {
// make required changes
// again click on save button
} else {
//break and exit
System.out.println("cic" + name);
finalString = finalString + "cic: " + name;
break;
}
}

Wait until text is not present in textbox selenium

Below is the scenario I am trying to automate:
1) Some text is already present in Textbox.
2) Click on Radio button.
3) Processing popup is displayed for few seconds. After popup disappears the textbox
becomes blank
4) After textbox is blank then I have to enter different value in text box.
Please help me, how to wait till textbox value is blank.
I am automating with IE driver.
Thanks In advance
I would try:
int timeout = 10; // depends on your needs
WebDriverWait myWait= new WebDriverWait(driver,timeout);
myWait.until(ExpectedCondition.textToBePresentInElementValue(By locator, String text))
-- with empty string passed as text argument
You can try something like this :-
public void waitUntilTextNotToBeInWebElement(WebElement element, String textValue) {
int timer = 0;
final int pollInterval = 500;
while (timer < MAX_TIME*1000) {
if (element.getText().equalsIgnoreCase(textValue)) {
sleep(500);
timer += pollInterval;
} else {
return;
}
}
throw new TimeoutException("Maximum time exceeded.");
}
Hi there is two possible way through which you can do this
1.Use Expected condition
// after you have clicked on radio button and it does some processing
WebDriverWait wait = new WebDriverWait(driver,30);
wait.until(ExpectedConditions.invisibilityOfElementWithText(locator, "your text"));
// now perform your operation
use if else
// get the text of input box like below
String myInitialText = driver.findElement(By.xpath("")).getAttribute("value");
// click on radio button
// now apply the logic
if(myInitialText == null){
System.out.println("Input box is blank");
// perform next operation
}else{
Thread.sleep(5000);
}
// now fill the input box
Below code worked for me.
WebElement element=driver.findElement(By.id("ctl00_cphClaimFlow_tabcontainerClaimFlow_tabFulfillment_Shipping_ctl33_txtStreeAddress1"));
String myInitialText=element.getAttribute("value");
//click on radio btn
driver.findElement(By.id("ctl00_cphClaimFlow_tabcontainerClaimFlow_tabFulfillment_Shipping_ctl33_radNewAddress")).click();
logger.info("New Address radio button clicked");
System.out.println("1 "+myInitialText);
while(!myInitialText.equals("")){
try {
Thread.sleep(5000);
logger.info("Thread is sleeping");
//System.out.println("2 "+myInitialText);
myInitialText=driver.findElement(By.id("ctl00_cphClaimFlow_tabcontainerClaimFlow_tabFulfillment_Shipping_ctl33_txtStreeAddress1")).getAttribute("value");
//System.out.println("3 "+myInitialText);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
driver.findElement(By.id("ctl00_cphClaimFlow_tabcontainerClaimFlow_tabFulfillment_Shipping_ctl33_txtStreeAddress1")).sendKeys(td.getAddressLine1().get(0));
logger.info("Address Line1 entered");

Categories