i have a project in eclipse for selenium test.
my project contains Test.class and Utility.class
In my Utility.class i have a method like:
public static void UsernameElement(){
try {
driver.findElement(By.xpath(Component._usernamef)).isDisplayed();
System.out.println(" username field is displayed [TEST PASSED]");
} catch (NoSuchElementException e) {
System.out.println("Username field is not displayed [TEST FAILED]");
} finally {
System.out.println("");
}
}
And then in my Test.class, i call the method like this:
Utility.UsernameElement();
Then i got this error:
"The method UsernameElement() is undefined for the type Utility"
i do not know i should put inside bracket in Utility.Username();
Can someone give a clue please. Thank you
Related
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
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. :)
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.
In Selenium, if a step fails for a test case, is it possible to just report the failure and continue with remaining steps? Currently the execution halts if there is an exception. This is what my Test case looks like-
public class TC002_abc extends OpentapWrappers
{
#Test (description="Test")
public void main()
{
try
{
WebDriverWait wait=new WebDriverWait(driver, 60);
VerifyTitle(Constant.HomePage_Title);
Click(HomePage.link_Login(driver), "Login Link");
wait.until(ExpectedConditions.urlContains(Constant.LoginURL));
VerifyTextPopulated(CommunicationPref.lbl_EmailAddress_Input(driver), Constant.EmailAddress);
/* Validate Email Communications */
Click(CommunicationPref.link_EditEmailCommunications(driver),"Edit Email Communications");
VerifyText(CommunicationPref.lbl_UnCheckedEmailCommunications(driver), Constant.UnCheckedEmailCommunications_Text);
Click(CommunicationPref.btn_EmailCommunicationsSave(driver), "Save");
VerifyText(CommunicationPref.lbl_CheckedEmailCommunications(driver), Constant.CheckedEmailCommunications_Text);
}
catch (NoSuchElementException e)
{
e.printStackTrace();
Reporter.reportStep("NoSuchElementException" , "FAIL");
}
}
#BeforeClass
public void beforeClass()
{
browserName="firefox";
testCaseName = "TC002_abc";
testDescription = "Test";
}
}
Sample Method-
public static void VerifyTitle(String title){
try
{
if (driver.getTitle().equalsIgnoreCase(title))
{
Reporter.reportStep("Page is successfully loaded :"+title, "PASS");
}
else
Reporter.reportStep("Page Title :"+driver.getTitle()+" did not match with :"+title, "FAIL");
}
catch (Exception e)
{
e.printStackTrace();
Reporter.reportStep("The title did not match", "FAIL");
}
}
Since you're using TestNG, implement a Soft Assertion
public void VerifyTitle(String title)
{
SoftAssert assertion = new SoftAssert();
String returnedTitle = driver.getTitle();
if (assertion.assertTrue(returnedTitle.contains(title)))
{
Reporter.reportStep("Page is successfully loaded :" + title, "PASS");
} else
{
Reporter.reportStep("Page Title :" + driver.getTitle() + " did not match with :" + title, "FAIL");
}
}
Let me know if this helps.
if a step fails for a test case, is it possible to just report the
failure and continue with remaining steps?
Short answer: YES
Long answer: YES
Selenium is framework built on top of a test engine such as JUnit or TestNG. On those engines, if you do nothing, the tool will interpret as a pass. In other words, in the absence of an assertion, the engines will assume the test passed. Since Selenium is built on top of this, the same can be said about Selenium. The code snippet below is a representation of what a Cucumber step looks like.
#When("my test step here")
public void myTestStep(...) {
boolean result = false;
try {
result = myTest(...);
}
} catch (Exception e) {
// log your exception (don't rethrow)
}
if (result) {
// log your passing test
} else {
// log your failing test
Assert.fail(); // This is what prevents subsequent steps to be executed. Remove it, and you should be able to continue to test.
}
For a JUnit or TestNG style method is basically the same. You may have an #AfterClass or #AfterTest hook that might handle telling the test framework to pass of fail test. TYPICALLY, passing assertions are implied (by not doing anything - i.e. executing an empty method). However, failing assertions are EXPLICIT and must be included somewhere. Just look for those Assert.fail() methods and remove them. A better alternative is to add a configurable property to your test suite that will turn this on or off.
} else {
// log your failing test
if (skip_off) {
Assert.fail(); // This is what prevents subsequent steps to be executed. Remove it, and you should be able to continue to test.
}
}
In this context, skip_off is the value of Boolean property you might have stored in a configuration file that when set to true, it will skip enforcing fail assertions.
Can anyone tell me where I'm going wrong in my program to get this error? I've put an "*" next to the lines which give me this error. Using Eclipse btw. The whole code is linked below. Thanks!!
public static void main(String[] args)
{
openFile();
addRecords();
closeFile();
}
public static void openFile()
{
try
*{
* output = new Formatter("numbers.txt");
*}
*catch
{
System.err.println("Write permission denied. Terminating.");
System.exit(1);
}
*catch
{
System.err.println("Error opening file. Terminating.");
System.exit(1);
}
}
http://pastebin.com/CKPQzCNi
Your catch clause is an exception handler which takes in an argument. The argument type, ExceptionType must be declared and must be the name of a class that inherits from the Throwable class. I see your try-catch block is not specifying an argument to either of the catch clauses.
Refer to the method addRecords() in the code you have referenced on pastebin for an example of correct exception handling.
Suppose, I am testing method which checks whether all links are present on page. Ex :
#Test
public void testLinks(){
driver.findElement(By.linkText("link1"));
driver.findElement(By.linkText("link2"));
driver.findElement(By.linkText("link3"));
driver.findElement(By.linkText("link4"));
driver.findElement(By.linkText("link5"));
}
In above code, suppose all links are present except link3 then test method's execution will stop after throwing error for link3 but still if I want code to be executed for checking link4 and link5, how can I achieve that using Java?
I think you mean throwing exceptions.
You can test links one by one in another method which handle exceptions.
public void testOne(String link) {
try {
driver.findElement(By.linkText(link));
}
catch (Exception e) {
System.out.println(link+" failed to find");
}
}
public void test() {
testOne("link1");
testOne("link2");
testOne("link3");
testOne("link4");
testOne("link5");
}
The testOne() method will catch exceptions and print a failed note, and your test method won't be disrupted.
Try this, you can use TestNg reporter to make your test pass or fail or log4j logs, try this.
sResult = "Pass";
public void testOne(String link) {
try {
driver.findElement(By.linkText(link));
}
catch (Exception e) {
System.out.println(link+" failed to find");
sResult = "Fail";
}
}
public void test() {
testOne("link1");
testOne("link2");
testOne("link3");
testOne("link4");
testOne("link5");
}
if(sResult.equals("Pass")){
System.out.println("Pass");
}else{
System.out.println("Fail");
}
I have a a method that is being called from Main but when the time comes to call the static method within it will not proceed and test stops.
I have inserted log comments in order to tell where the problem is and no exceptions are caught so there is no compiling nor runtime errors so far.
The static method that is not being called is GC2CommonMethods.loadApplication();.
The weird thing is that when running Main from Eclipse IDE it runs perfectly but it does not when executing from jar file through the same Main method.
See below both codes from the method that is being executed and the detail of the static method that is within a static class respectively.
I would appreciate your help with this. Thanks.
//This method is intented to be called from Main method
package com.mycompany.test.loginRoleEntitlements;
public void verifyLoginPageElements() {
logger.info("\t1.0/1.0.2 - Verif**strong text**ying Login page elements...");
try {
logger.info("entering Try");
GC2CommonMethods.loadApplication(sl); //Static method from Static class.
assertTrue("Region identifier is not present.", sl.isElementPresent(PageAttributes.LoginPage.DB_LABEL));
assertTrue("Forgot Password link is not present", sl.isElementPresent(PageAttributes.LoginPage.FORGOT_PASSWORD));
} catch (SeleniumException se) {
logger.info("caught SeleniumException");
logger.error(se.getMessage());
throw se;
} catch (AssertionFailedError ae) {
logger.info("caught AssertionException");
logger.error(ae.getMessage());
throw ae;
} catch (Exception e) {
logger.info("caught Exception");
logger.info("Encountered exception");
e.printStackTrace();
}
//This is the static method that is within GC2CommonMethods static class
package com.mycompay.common;
public static void loadApplication(SeleniumHandle sl) {
sl.open(props.getProperty("APPLICATION_URL"));
sl.waitForPageToLoad("30000");
assertEquals("The page is not the correct one.
|Expected: "+PageAttributes.LoginPage.LOGINPAGE_TITLE + ".
Found:"+sl.getTitle(),PageAttributes.LoginPage.LOGINPAGE_TITLE,sl.getTitle());
}
I found the solution. The problem was on the main method when trying to read a properties file. There was an uncaught exception which was not being logged so I was not able tell where the problem was. Thanks for your replies.