Execute selenium click with ID based on different classes in Java - java

I have two selenium elements where i need to click. But these elements are with a different id.
findElement(By.id(ID_1)).click();
findElement(By.id(ID_2)).click();
findElement(By.id(ID_1)).click() should be clicked if the Class_1 is executed, if Class_2 is called, then findElement(By.id(ID_2)).click() should be clicked.
I am trying to avoid duplicate code because these above 2 find elements are inside one method which is called Class_1 and Class_2.
I tried something like this but it didn't solve my issue
if (Class_1.class)
{
findElement(By.id(ID_1)).click();
}
else if (Class_2.class)
{
findElement(By.id(ID_2)).click();
}
I am getting "Type mismatch: cannot convert from Class<Class_1> to boolean". I mean I am trying to do like this. If this is class_1, then run this, else run else if part.
Thanks for any guidance in advance.

You schouldn't separate your test into two (or more) different classes.
Instead use one class and parametrize your method:
public void myTestMethod(String ipAdress) {
if (ipAdress.equals("FOO_IP")) {
findElement(By.id("FOO_ID")).click();
}
else if (ipAdress.equals("BAR_IP")) {
findElement(By.id("BAR_ID")).click();
}
else {
// code for uknown ip adress
}
}
and simply call the method with desired argument:
myTestMethod("FOO_IP");
myTestMethod("BAR_IP");

Related

Passing a String to another class [duplicate]

This question already has answers here:
Pass a class variable to another class
(3 answers)
Closed 4 years ago.
I'm stuck on a simple problem that I just can't solve.
I have two classes (Fruits.java with main and FruitDetails.java).
Fruits.java is a small program with tons of stuff, really. It has a ComboBox and I need to transfer its currently selected option to FruitDetails.
The problem is... my understanding of setters and getters seems to be very flawed. I've researched it online for the last 2 hours and this is the closest I could get to something. I'm really tight on time and I can't help but ask you now...
Inside class Fruits.java
public void selectedFruit() {
currentFruit = (String) fruitList.getSelectedItem();
}
public String getSelectedFruit() {
return currentFruit;
}
Inside class FruitDetails.java
public void fruitChoice() {
Fruits fruitChoice = new Fruits();
String chosenFruit = fruitChoice.getSelectedFruit();
System.out.println(chosenFruit);
// Rest of the code
}
Not only this opens another copy of my program(which I really don't want), system prints out "null" for the result.
I really need to get this working and hopefully it'll help fix my understanding of encapsulation a bit. There's a ton of online resources I've found, but using them seems to be too hard for the thick head of mine.
Thanks in advance for any help.
public void fruitChoice() {
Fruits fruitChoice = new Fruits();
String chosenFruit = fruitChoice.getSelectedFruit();
System.out.println(chosenFruit);
// Rest of the code
}
In second line you are creating new object that's why you are getting null when you try to get the value of currentFruit.
it looks like you method selectedFruit() sets currentFruit but your not actually calling selectedFruit()?
Unless your missing some code above that calls selectedFruit() elsewhere?
Try calling selectedFruit() after instantiating your Fruit object.
This is because you have not actually linked your currentFruit to your combo box. You need to do two things - call selectedFruit when you first populate the combo box, then attach a listener that calls selectedFruit everytime the combo box selection changes.
If you are using JComboBox, insert this code after you have created the JComboBox.
combo.addActionListener (new ActionListener () {
public void actionPerformed(ActionEvent e) {
selectedFruit();
}
})
selectedFruit();

How to get a single output by 2 different way of the process using selenium webdriver?

I am working on selenium and TestNG with java. I have some problem about how to handle the popup. In here, I have 2 process at a time. if I click on the button and it has an ingredient, then it will open a popup, otherwise it will add in a cart directly. So i used:
#Test
public void ingredient_Popup()
{
String ingre_Title="Choose product choices...";
String ingre_Title1=d.findElement(By.className("modal-dialog")).getText();
if(ingre_Title.contentEquals(ingre_Title1))
{
d.findElement(By.id("ingredient_quantity")).sendKeys("1");
d.findElement(By.linkText("SUBMIT")).click();
}
else
{
d.findElement(By.xpath("/html/body/section[3]/div[2]/div/div/div/div/div/div[1]/div[3]/div/div/div[3]/div/div[1]/table/tbody/tr/td[2]/div/span[2]/button")).click();
}
And also i used (II)
#Test
public void ingredient_Popup()WebElement element;
try
{
element = d.findElement(By.className("modal-dialog")); >}
catch(NoSuchElementException n)
{
element = null;
}
{
if(element !=null)
{
d.findElement(By.id("ingredient_quantity")).sendKeys("1");
d.findElement(By.linkText("SUBMIT")).click();
}
else
{
d.findElement(By.className("btn btn-default btn-number")).click();
}
}
And i used, isenabled, Contains, equals, isdisplayed, isElementPresent
if(ingre_Title.isEnabled())
{
d.findElement(By.id("ingredient_quantity")).sendKeys("1");
d.findElement(By.linkText("SUBMIT")).click();
}
else
{
d.findElement(By.xpath("/html/body/section[3]/div[2]/div/div/div/div/div/div[1]/div[3]/div/div/div[3]/div/div[1]/table/tbody/tr/td[2]/div/span[2]/button")).click();
}
And i tried a lot, Nothing is working. i'm getting NoSuchElementException
error.
So Kindly anyone make a code and share it with me.
Here the issue is to identify the scenario correctly. Just find the existence of the expected element in case of that particular scenario else otherwise.
For example, consider after clicking a button you might have two scenario's. Scenario A has element A and scenario B has element B then,
driver.findelement(By.xpath("button")).click;
//Identifying the scenario by checking the presence of the element
if(driver.findElements(By.xpath("A")).size>0)
{
//IF THIS IS TRUE NOW YOU ARE IN SCENARIO A
//DO YOUR STUFF ACCORDING TO SCENARIO A
}
else if(driver.findElements(By.xpath("B")).size>0)
{
//IF THIS IS TRUE NOW YOU ARE IN SCENARIO B
//DO YOUR STUFF INCASE OF SCENARIO B
}
Modify the logic as per your logic but the trick is in findelements. You can use this to check the presence of an element easily.
Hope this helps.
Thanks.

Returning multplie values of the same type in Java

I need to return 3 values of an object I created in a method I created. I can put this code in my while loop and it executes how I want it to execute. But I want to keep it in a method just to modularize my program and keep the code organized. Im using the ACM library which is for academia purposes.
public GObject asteroidLocation(){
if(asteroid1.getX() >= AW)
{
asteroid1.setLocation(0,150);
}
else if(asteroid2.getX() >= AW)
{
asteroid2.setLocation(0,80);
}
else if(asteroid3.getX() >= AW)
{
asteroid3.setLocation(0,20);
}
return asteroid1, asteroid2, asteroid3;
}
What you need is a java.util.List
For your use-case you could just do this:
return Arrays.asList(asteroid1, asteroid2, asteroid3);
Your return type then would be List<GObject>
So return a List<Asteroid> or whatever type asteroid is. Even better is have an object you create that has a List<Asteroid>, has a getAsteroids() method and return that.
Have you tried Tuples (https://en.m.wikipedia.org/wiki/Tuple) and Triples?
Java don't provide any but it's pretty straightforward to implement. I can give you an example if needed.
Instead of returning the value outside the if condition return it from within. For example,
if(asteroid1.getX >= AW)
{
asteroid1.setLocation(0,150);
return asteroid1;
}
This way you could simplify the code and pass only one return value to the class
A direct answer to you question "multplie values of the same type in Java" would be:
An array: GObject[]
Any generic collection, e.g. List<GObject>

Is it possible use #NotifyChange instead of BindUtils.postNotifyChange?

I have one confusion use between #NotifyChange and BindUtils.postNotifyChange ,Why use this two event .Before i read this question
In ZK Can we PostNotifyChange more than one variables .
But i cant understand this question why use this more than one variable.
Here's an example:
#Command
#NotifyChange({ "folderInfoList", "isDisabled", "selectedFolderInfo" })
public void refreshFolderInfo() {
logger.debug("Refresh Icon selected");
if (isDirty()) {
Messagebox.show(pageResourceBundle.getText("JS_CONFIRM_DATAMODIFED"), pageResourceBundle.getText("JS_CONFIRM_DATAMODIFED_TYPE"),
Messagebox.OK | Messagebox.CANCEL, Messagebox.QUESTION, new EventListener<Event>() {
public void onEvent(Event event) throws Exception {
if (Messagebox.ON_OK.equals(event.getName())) {
loadFolderInfoList();
selectedFolderInfo = null;
BindUtils.postNotifyChange(null, null, FolderInfoEditViewModel.this, "folderInfoList");
} else {
}
}
});
} else {
loadFolderInfoList();
selectedFolderInfo = null;
}
}
Can anybody tell me:
I have four question :
1.Why use isDisabled in #NotifyChange ?
2.Here this method i can use #NotifyChange instead of BindUtils.postNotifyChange ?
3.What is the difference between #NotifyChange and BindUtils.postNotifyChange ?
4.I want to use only one event between this two #NotifyChange and BindUtils.postNotifyChange in method .Is it possible for this method ?
1) If the variable associated with "isDisabled" is not changed in any case by this call, you don't need to.
But maybe it is changed inside loadFolderInfoList()
2) You can imagine that a #NotifyChange({"arg1","arg2",...,"argN"}) is the same as
for(String arg : args){
BindUtils.postNotifyChange(null, null, refToClassCalledFrom, arg);
}
3) But you can call BindUtils.postNotifyChange(...) from everywhere as long as you got a reference to the VM.
4) To me it looks like this code is from a nested class of FolderInfoEditViewModel, that it self is is VM as well as FolderInfoEditViewModel.
In this case the #NotifyChage(...) is invoked for the nested class but
BindUtils.postNotifyChange(null, null, FolderInfoEditViewModel.this, "folderInfoList");
refers to it's outer class FolderInfoEditViewModel and that can only be archived this way.

I don't want to write driver.findelement(By.xpath("")) again and again

Hi this is the code below: What I want to do is this build a function in which i just pass the value of XPath, so i don't have to write driver.findElement(By.xpath("")) again and again.
driver.findElement(By.xpath("//*[#id='lead_source']")).sendKeys("Existing Customer");
driver.findElement(By.xpath("//*[#id='date_closed']")).sendKeys("08/07/2013");
driver.findElement(By.xpath("//*[#id='sales_stage']")).sendKeys("Opportuntiy Qualification");
driver.findElement(By.xpath("//*[#id='opportunity_monthly_volume']")).sendKeys("10895");
driver.findElement(By.xpath("//*[#id='probability']")).sendKeys("90");
driver.findElement(By.xpath("//*[#id='opportunity_sales_rep']")).sendKeys("Sales Rep");
driver.findElement(By.xpath("//*[#id='opportunity_sales_regions']")).sendKeys("Northeast");
driver.findElement(By.xpath("//*[#id='opportunity_current_lab']")).sendKeys("Current lab");
driver.findElement(By.cssSelector(Payermixcss +"opportunity_medicare")).sendKeys("5");
The best way would be to use the PageObject pattern. You could do something like this:
public class MyFormPageObject {
public MyFormPageObject enterLeadSource(String value) {
driver.findElement(By.id("lead_source")).sendKeys(value);
return this;
}
public MyFormPageObject enterDateClosed(String value) {
driver.findElement(By.id("date_closed")).sendKeys(value);
return this;
}
//...
}
// then in your test code
myFormPO.enterLeadSource("Existing Customer").enter("08/07/2013");
Note that as mentionned, you should use By.id if you have an identifier, because XPath is slower and not always well supported by all implementation of WebDriver.
Extract a method to upper level and just pass the values as parameters
eg:
yourMethod(Path path) {
driver.findElement(By.xpath(path))
}
As per your concern you can you use page object model and create the method and pass the variable to exact method.. I don't konw java but i know and concepts
private string variable= "Xpath value"
Pass this variable to method and it will interact with POM.. Before that u should know about POM. Then u can easily understand the concepts. Hope it will help full you...
To reduce the amount of code you have to write, you could use a function like this:
private WebElement findElementByXpath(String xpath) {
return driver.findElement(By.xpath(xpath));
}
The first line of your code would be:
findElementByXpath("//*[#id='lead_source']").sendKeys("Existing Customer");
It does not really reduce the length of the code but it only takes one CTRL + SPACE for autocompletion in Eclipse IDE.

Categories

Resources