Reputation: 587
i have a class Test1 where i use this line to click on a button:
try{
driver.findElement (By.xpath(Component._emp)).click();
System.out.println("Employment is clicked");
} catch (NoSuchElementException e17) {
System.out.println("Employment is not found [TEST FAILED]");
}
And another class named Util, in this class i copied the code above like this:
public static void click_person_employment(){
try{
driver.findElement (By.xpath(Component._emp)).click();
System.out.println("Employment is clicked");
} catch (NoSuchElementException e17) {
System.out.println("Employment is not found [TEST FAILED]");
}
}
So in my class Test1 when i call like this: Util.click_person_employment()
it throws java.lang.Nullpointer exception
Whta is the proper way to call this method. My goal is to reduce code in my class Test1 because i have more than 100 buttons to click. Thank you
Upvotes: 2
Views: 2462
Reputation: 2115
To achieve your goal, you can follow the below way:
First return WebElement
from the Util class method -
public static WebElement click_person_employment(String empPath){
WebElement elem = null;
try{
elem = driver.findElement(By.xpath(empPath));
//System.out.println("Employment is clicked");
} catch (NoSuchElementException e17) {
System.out.println("Employment is not found [TEST FAILED]");
}
return elem;
}
Then call this method from Test1 class like
String empXpathStr = Component._emp;
WebElement element = Util.click_person_employment(empXpathStr);
element.click();
//Use WebDriverWait wait functionality here [Wait until element is visible]
You can also try removing the static
keyword and creating the instance of Util class in your Test1 class. Finally call the method from Test1 class using the instance object.
Upvotes: 1
Reputation: 387
I would recommend creating more general methods in your Utils class, ones that you can reuse over and over.
Also, System.out.println is not recommended in code. Instead you can use a logging framework - SLF4J is a good one. If you insist on using System.out.println, you can pass on the message as well.
So I'd do something like:
private static final Logger LOGGER = Logger.getLogger([className].class.getName());
public static void clickOnElement(By by){
try {
WebElement element = driver.findElement(by).click();
} catch (NoSuchElementException e) {
LOGGER.log(Level.WARNING, e.getMessage(), e);
}
}
and then call it in test as:
Util.clickOnElement(By.xpath(...));
If you want the test to fail when the button is not found, you can rethrow the exception in the catch block.
PS. also, explicit waiting is always preferred to Thread.sleep - avoid that one in your tests as much as possible. :)
Upvotes: 1