Verify if a link is present or not - java

I'm trying to verify if a link is present or not -- but -- if it's not present, I want my script to continue executing (close the browser, etc).
The purpose of my script is to determine if a 'Delete Address' link is present or not. If it is, I click on the link and delete the address. This works fine. If the link is not present however, I just want to continue execution without triggering an exception. My code below triggers an exception if the link is not there.
Thanks for any help...
try {
String txt = driver.findElement(By.linkText("Delete Address")).getText().trim();
Assert.assertTrue(txt.equals("Delete Address"));
Alert javascriptprompt = driver.switchTo().alert();
javascriptprompt.accept();
} catch (NoSuchElementException e) {
}

I can see several options here
Do not use asserts in the test at all. In this case the test is marked as successful (if you caught exceptions)
If you want the lines after the findElement() call be executed you can
move all lines expect for findElement() out of the try {} clause
use the try {} catch {} finally {} construction and put to the finally {} clause all the code you want to be executed, no matter what happens in the try {}
If you want to avoid catching exception, you can create a listener class by implementing the interface ITestListener and in onTestFailure() obtain the exception using getThrowable()
String stackTraceString = Throwables.getStackTraceAsString(getCurrentTestResult().getThrowable());
Then, if the exception is NoSuchElementException then set test result to success
result.setStatus(ITestResult.SUCCESS);
setCurrentTestResult(result);

Another solution would be to use .findElements. It will return an empty collection, as opposed to throwing an exception, if there are no elements found with the given selector.

Related

Is there a point to handle exceptions in selenium besides for logging purposes?

I am finding it hard to understand the point of exception handling in selenium.
For example, if I try to click on an element, and the element could not be found then NoSuchElementException occurs.
I can catch the exception, throw new RunTimeException, or do nothing. The result will be the same ( the program will fail and stop ).
Why would I bother to handle such an exception?
Am I missing something here?
thanks
public void clickOnElement(MobileElement element, Integer waitInSeconds){
waitInSeconds = (waitInSeconds != null ? waitInSeconds : this.secondsToWait);
try {
waitFor(ExpectedConditions.elementToBeClickable(element),waitInSeconds);
element.click();
} catch (Exception e) {
System.out.println("Could not click on element");
e.printStackTrace();
}
}
Exception handling for Selenium is a great way to proof your tests against unexpected conditions. For example, you can try to find the element again if it is no longer attached to the page, for example after a javascript is executed that changes something in the element.
try{
driver.findElement(By.id("MyId")).click();
} catch (StaleElementReferenceException e){
driver.findElement(By.id("MyId")).click();
}
Or, for example, you can ignore if an element does not appear, for example, a GDPR overlay at the top of the page after logging in.
try {
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("gdpr_overlay")));
} catch (TimeoutException ignored){
}
This will ignore the exception thrown by the wait if the overlay does not appear and continue to run your test.
Exceptions are very useful features, far more useful than just for logging, you should look it up.
You can do whatever you want in the catch block, you can try to click a different element if the first one failed, redirect to another page... The possibilities are endless really.
Advice: Avoid generic exceptions, you should catch specific exceptions and react accordingly, and in the last catch block you can do generic Exception e and throw an error.
Firstly ExceptionHandling is not a concept of Selenium but it is related to JAVA. Now coming to the usage of handling exceptions it has a lot of depth to the concept which you will understand while constructing frameworks but as of now it is important to understand by handling exceptions you can continue to execute your code without JVM terminating the rest when it comes across an exception.
try{
}
catch{
}
finally
{
}
Finally is also very helpful when you always want to execute a block of code irrespective of whether ur scenario is going to pass or fail for example like driver.close().
Hope that helped ... Happy coding :)

How do I correctly handle errors like these in SQLite/Java/Android?

For example I have something like this:
public void saveFoodatas(List<Foodata> foodataList) {
DatabaseHelper.database.beginTransaction();
try {
for (Foodata foodata : foodataList) {
saveFoodata(foodata);
}
DatabaseHelper.database.setTransactionSuccessful();
}
finally {
DatabaseHelper.database.endTransaction();
}
}
Where DatabaseHelper is a class extending SQLiteOpenHelper and database is a SQLiteDatabase.
In this function I am trying to make it so you save/commit a lot of objects to the database, but if there is a failure, then don't commit any of the changes.
I believe that what it's currently set up to do correctly (if there is an error, it leaves the try block I think and goes straight to finally since there is no catch), but my question is how to properly trigger the failure condition. Do I need saveFoodata to "throw an exception"? If the function encounters some kind of failure without me doing any try/catch/throwing, does that count too? How exactly do I handle saveFooData()?
I think you are on the right track. You need to abort the transaction if an error occurs. You also need to alert the user of the problem. This means that saveFoodata() and saveFoodatas() should throw an exception so that the UI code can display a message to the user,

Using Assert containing wildcards (Selenium Webdriver)

I'm trying to use webdriver to check that something DOESN'T exist on the webpage (after it has been deleted by the user).
I'm using a try-catch method to handle the NoSuchElementException, but within the 'catch' I want to be able to assert that the NoSuchElementException contains the text "NoSuchElementException", and use wildcards for the rest of the exception (since other details within the exception change every time)
Here's what the bit of code looks like, as you can see I've tried to use a * as a wild card to indicate that nothing after the exception matters to me, I just want it to check that the exception is the correct one and pass the test based on that:
catch (NoSuchElementException e1)
{
Assert.assertEquals(e1, "org.openqa.selenium.NoSuchElementException: *");
}
You are catching NoSuchElementException and inside the catch block you are checking if it is a NoSuchElementException which does not add any value. You are testing if JDK works correctly.
To check if the element does not exist on page, you could use a method like this :
public boolean isElementPresent(By locatorKey) {
try {
driver.findElement(locatorKey);
return true;
} catch (org.openqa.selenium.NoSuchElementException e) {
return false;
}
}
You should then assert on the above method,
if element should not be present
Assert.assertFalse(isElementPresent(By.id("login")));
if element should be present
Assert.assertTrue(isElementPresent(By.id("login")));
I assume you are using TestNG assertions. If so, I would use contains to search for a partial match.
assertTrue(e1.getClass().toString.contains("org.openqa.selenium.NoSuchElementException:"));

Run a program without Try/Catch block

I'm making a sort of chat program in Java. Specifically, if I ask "can you open chrome?", the program will reply with "yes..." and then opens Google Chrome (Windows).
I have created the path to the Chrome as a string:
Runtime rt = Runtime.getRuntime()
String file="C:\\Program Files (x86)\\Google\\Chrome\\Application\\Chrome.exe";
I try to call the String, but says to either "Surround Statement with try/catch" or "Surround block with try/catch". Or the "Add throws clause to the "java.io.IOException" ".
myVocab.addPhrase("Can you open Chrome?", "Yes, one moment..." + rt.exec(file));
Whenever I do either of these, Chrome just opens automatically.
I'm somewhat new to Java so please tell me if there's an easier way to do this, or if I'm doing this completely wrong.
Some java functions need to be implemented with the try catch statements because it is possible to get an exception inside that function. An exception is defined as "An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions" more info
So, to manage an exception, for your case, you could:
try { code1 } catch (ExceptionType name) { code2 }
where ExceptionType should correspond to the possible error type your code1 could give you.
Ex:
try { //code to open google } catch (InterruptedException e) { e.printStackTrace(); }
e.printStackTrace(); will print error details

How to delete files from a USB Stick ? Using File.delete() doesn't work

after creating a file and populating it with that with a thread if the file is in a USB java can't delete it, when I try on disk it deletes the file ok !
Here is the part of the code that create and after an exception when try to delete the file.
if(canExport && fileCreated)
{
//Create the file
this.file.createNewFile();
//Export the data
this.run();
if(possible == false){ // in case writing fails delete the file created.
file.delete();
Export novaTentativa = new Export(plan);
novaTentativa.fileCreator(plan);
}
}
The file is created when the this.file.createNewFile() acts.
When this.run() runs, there is a lot of methods to populate the data and handle exceptions, if one exception is caught it sets the global variable possible to false so I know the file is created but empty in the USB, after that I try to delete it with file.delete();
You mention that you're trying to delete the file "after an exception" - consequently, your approach is on the wrong track and isn't going to work as-is.
If an exception is thrown by earlier methods (e.g. the createNewFile() call), then that exception will immediately propagate upwards, so your file.delete() call won't get a chance to execute. You'd need to wrap the earlier statements in a try block, and put the delete call in the corresponding catch or finally block in order for it to execute when an exception was thrown.
Here's an example of what you might try to do:
if(canExport && fileCreated)
{
//Create the file
this.file.createNewFile();
try
{
this.run();
}
catch (IOException e)
{
try
{
file.delete();
}
catch (IOException ignore) {} // don't want to mask the real exception
// Rethrow the actual exception from run() so callers can handle it
throw e;
}
}
An alternative approach rather than catching IOExceptions would be to have a finally block (which is always run) and then check a condition there, such as your possible flag.
Note as well that I start the try block after the call to createNewFile() - if an exception is thrown in the create file call then the file won't exist to delete at all!
As a file note, adding "a lot of code that asks for the thread to start over" in your error-handling block is probably not the best design. It would be more appropriate to simply consider recovering from IO situations here, and let the exception bubble up to the top and cause the thread/runnable to die. The logic around restarting tasks and/or resurrecting threads would be better positioned with the class that started the threads in the first place (e.g. a thread pool/task executor/etc.). Scattering the logic throughout the code will make it harder to see what any individual class is doing (not to mention that having a class marshall resources to resurrect itself just seems wrong from an OO standpoint).
Try explicitly stating the drive letter, path and folder to access the USB device to create write and read or delete the file. If that does not work then it is possible only a specific operating system utility or proprietory utility can delete the file.
How certain are you that you closed the file when the write failed? I'll bet money that you are missing a finally block somewhere in this.run(). That would result in exactly the behavior you describe - delete() will fail if the file is open (you should check it's return code - File.delete() doesn't throw exceptions if it is unable to delete the file).
If you want to test this, replace this.run() with a super, crazy simple implementation that writes 100 bytes to the file, sets 'possible' to false, then returns. If the file still won't delete, post the code you are using for this simplified version of run() and maybe someone can spot what's going on.

Categories