I always encounter this exception during my batch run.
I've already catch the InterruptedException then call the Thread.currentThread.interrupt().
How can I get rid of the sleep interrupted?
I encountered randomly in WebDriverWait. I don't know why it happens.
public boolean isElementVisible(WebElement webElement) {
boolean isVisible = false;
try {
log.info(CHECK_IF_ELEMENT_IS_VISIBLE);
WebDriverWait wait = new WebDriverWait(driver,
CommonConstants.DEFAULT_TIMEOUT_IMPLICITWAIT);
Wait.until(ExpectedConditions.visibilityOf(webElement));
isVisible = true;
} catch (Exception e) {
log.error(ELEMENT_NOT_FOUND, e);
}
return isVisible;
}
Related
I am stuck in a scenario, where user is allowed to rate the movie only once a day with same user credentials.
If user tried to rate the same movie or contract, error pop_up seen.
I want to Implement in a way, that if once any movie/contract is rated. The rating functionality should be skipped and Error pop should be Handled.
I am using Selenium eclipse 2017, Chrome browser 61.0 and Test-Ng
Please help in the same.
Thanks.
public class Ratings {
String driverPath = "F:/ChromeDriver/chromedriver.exe";
public WebDriver driver;
public Alert alert;
#BeforeTest
public void LaunchBrowser () throws InterruptedException {
System.out.println("WebBrowser open");
System.setProperty("webdriver.chrome.driver","F:/ChromeDriver/chromedriver.e
xe");
driver = new ChromeDriver();
driver.manage().window().maximize();
}
#Test (priority = 1, alwaysRun = true)
public void HomePageUSA() throws InterruptedException {
driver.navigate().to("Https://us.justdial.com");
String expectedTitle = "Justdial US";
String actualTitle = driver.getTitle();
try
{
AssertJUnit.assertEquals(expectedTitle, actualTitle);
System.out.println("Test Passed");
}
catch (Throwable e)
{
System.out.println("Test Failed");
}
Thread.sleep(3000);
}
#Test (priority = 2, dependsOnMethods = {"HomePageUSA"})
public void Login() throws Exception{
Thread.sleep(3000);
driver.findElement(By.xpath("/html/body/div/div[1]/div[1]/div[1]/div/div/div
/div[4]/aside/div/span/a[1]")).click();
driver.findElement(By.id("inputPassword3")).clear();
driver.findElement(By.id("inputPassword3")).sendKeys("testing.testjd#gmail.c
om");
driver.findElement(By.id("exampleInputPassword1")).clear();
driver.findElement(By.id("exampleInputPassword1")).sendKeys("justdial");
driver.findElement(By.xpath("/html/body/div[4]/div[2]/div[1]/section/div/div
[1]/div/form/div[3]/div/button")).click();
Thread.sleep(1000);
String expectedTitle = "Justdial US";
String actualTitle = driver.getTitle();
try
{
Assert.assertEquals(expectedTitle, actualTitle);
System.out.println("Login Successful");
}
catch (Throwable e)
{
System.out.println("Login Failed");
}
Thread.sleep(1000);
driver.findElement(By.xpath(".//*[#id='us-jdnew-
wrapper']/div[1]/div/header/div/div[1]/a[2]")).click();
Thread.sleep(2000);
}
#Test (priority = 3)
public void Movies_Rating_page() throws Exception {
driver.findElement(By.xpath(".//*[#id='hotkeylnk106']/div[2]")).click();
Thread.sleep(2000);
driver.findElement(By.xpath(".//*[#id='main-
wrapper']/div/div/div[3]/div[2]/div/div[1]/div[1]/div/a/span/img")).click();
Thread.sleep(2000);
driver.findElement(By.xpath(".//*[#id='main-
wrapper']/div/div/div[2]/div[1]/ul/li[2]/span/a[2]/span[1]")).click();
Thread.sleep(3000);
driver.findElement(By.xpath(".//*
[#id='AlreadyRated']/div/div/div/section/div/a")).click();
System.out.println("Rating Page Redirection Successful");
Thread.sleep(3000);
driver.findElement(By.xpath(".//*[#id='us-jdnew-
wrapper']/div/form/div/div/div/div[2]/span[2]/span[10]")).click();
Thread.sleep(1000);
driver.findElement(By.xpath(".//*[#id='us-jdnew-
wrapper']/div/form/div/div/div/div[3]/div[3]/textarea")).sendKeys("Very nice
movie, Must watch.");
Thread.sleep(1000);
driver.findElement(By.xpath(".//*[#id='us-jdnew-
wrapper']/div/form/div/div/div/div[3]/div[4]/button[2]")).click();
Thread.sleep(3000);
System.out.println("Rating Successfully Submitted");
You can create a method and tag that method in your test method as dependsOnMethods . You can achieve it like below (i tried to answer to the best based on the info provided)
The idea here is that when your rated condition is met isMovieRated should throw exception so that Movies_Rating_page() will be skipped by testNG ,otherwise isMovieRated just returns true and nothing should be skip.
#Test
public static boolean isMovieRated(String locator) {
//check in "if" below that element has already clicked or is equal to something. I used 'AlreadyClicked' just to
give an idea as I dont have your application information.
if (driver.findElement(By.xpath(locator).getText()=="AlreadyClicked"){
throw new RuntimeException();
}
else {
return true;
}
}
Now your Movies_Rating_page() will look like this
#Test (priority = 3,dependsOnMethods = { "isMovieRated" })
public void Movies_Rating_page() throws Exception {
public static String YourLocator = "/html/body/...."
Ratings.isMovieRated(YourLocator);
..
}
here is a link for more info on testNG dependsOnMethods
Note:
The code above is not tested.
If you are doing things other than checking rating in Movies_Rating_page() then you should separate those things because everything will be skipped when an exception is thrown.
Hope this helps.
I'm performing a Database operation in the doInBackground method inside an AsyncTask on Android.
For some reason, the UI get blocked during the 5-6 seconds that the operation takes.
It does not make any sense for me, the operacion inside the doInBackground should not be executed in the UI Thread, right?
Here is my code:
private class CountItems extends AsyncTask<String, Void, Integer> {
private ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(context);
dialog.setCancelable(false);
dialog.setMessage(getString(R.string.asynTask_loading));
dialog.show();
}
#Override
protected Integer doInBackground(String... params) {
// This operation takes 5-6 seconds.
return app.databaseSession().getMyObjectDao().count(selectedProject, filter, null, false);
}
#Override
protected void onPostExecute(Integer result) {
counterTextView.setText(String.valueOf(result));
if (dialog.isShowing()) {
dialog.dismiss();
}
}
}
I've made a test. If I put a Thread.sleep() inside the doInBackground method, it is executed in a different Thread without blocking the UI.
Like this:
#Override
protected Integer doInBackground(String... params) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 0;
}
Any ideas?
Thanks in advance.
I am trying to implement a method 'waitForNewWindow' in Java using selenium WebDriver. This method is all about waiting to check if a new window is opened. If a new window is opened in the specified time, i need to return true, else return false.
public boolean waitForNewWindow(String target) {
try {
Thread.sleep(30000);
if(driver.switchTo().window(target)!=null) {
log.info("New window is opened");
return true;
}
}catch(Exception e) {
log.debug(e);
return false;
}
return true;
}
But here, I don't want to use thread.sleep(time). The waiting time needs to be specified as below:
WebDriverWait wait = new WebDriverWait(driver, TIMEOUT);
Moreover, in the above code, the control is switching to the new window, which is not expected. Can someone please provide your answers on how to implement my requirement?
the below mentioned code checks for the number of windows to appear with time out
public void waitForNumberOfWindows(final int length){
new WebDriverWait(driver, 30) {
}.until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver driver) {
return driver.getWindowHandle().length()==length;
}
});
}
it will check for the expected number of windows to be present at that instance and will return true if the count matches with in the specified timeout(30 in above code)
You can not specify a timeout like you want. You have to use Thread.sleep().
Regarding your control moving to new window because of your below line the control is moving to new tab
driver.switchTo().window(target)
If you want to simply check if there is two windows open or not, you can write something like below
while( driver.getWindowHandle().length() != 2){
Thread.sleep(2000);
}
Finally got the implementation of waitForNewWindow method, using the WebDriverWait object as below:
try {
ExpectedCondition<Boolean> e = new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver wd) {
if (wd.switchTo().window(newTarget) != null) {
log.info("New window is opened with the window id : "
+ newTarget);
driver.switchTo().window(parentHandle);
return true;
} else {
return false;
}
}
};
WebDriverWait wait = new WebDriverWait(driver, TIMEOUT);
if (wait.until(e)) {
log.info("the wait for the expected condition is successful");
return true;
}
} catch (Exception e1) {
log.debug(e1);
return false;
}
Tested the same and its working fine.
I am using Threadpool.QueueUserWorkItem like following
public void TestMain()
{
try
{
ThreadPool.QueueUserWorkItem(x =>
{
this.Dispatcher.BeginInvoke(new Action(() => this.BackGroundMethod()));
}
);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void BackGroundMethod()
{
try
{
int a = 0;
int b = 100;
var error = b / a;
}
catch(Exception)
{
throw;
}
}
By this way, TestMain() can not catch exception.
Program will shut down...
How can i catch this error?
Thx.
The reason is this.Dispatcher.BeginInvoke(new Action(() => this.BackGroundMethod)); executes asynchonously, so it will finished execute all code inside TestMain before BackGroundMethod is executed.
Use Dispatcher.UnhandledException event to catch the exception in the TestMain() method like this:
Dispatcher.UnhandledException += (sender, args) => MessageBox.Show(args.Exception.Message);
ThreadPool.QueueUserWorkItem(ignore => Dispatcher.Invoke(new Action(BackGroundMethod)));
Edit: Remember to set the Handled property to prevent the internal exception handler from being called:
Dispatcher.UnhandledException += (sender, args) =>
{
MessageBox.Show(args.Exception.Message);
args.Handled = true;
}
To prevent the crash, add a try/catch around the operation which might throw:
ThreadPool.QueueUserWorkItem(x =>
{
try {
this.Dispatcher.BeginInvoke(new Action(() => this.BackGroundMethod()));
}
catch (DivideByZeroException ex) {
// handle the error somehow
}
});
However, think about what you are doing here: you are pushing some action to the thread pool, and in turn it pushes the same action to the dispatcher thread. Why not do this yourself directly without the QueueUserWorkItem call?
You can catch all exceptions in all threads within the application by handling AppDomain.UnhandledException
When you use the Dispatcher to create a new thread, that thread has it's own stack, and so the exceptions wont bubble to the try...catch in TestMain, but instead they will originate in BackgroundMethod method. As you are throwing the exception in BackgroundMethod your try catch is useless, and so if you were to not throw the exception in BackgroundMethod your program wouldn't shut down.
private void BackGroundMethod()
{
try
{
int a = 0;
int b = 100;
var error = b / a;
}
catch(Exception)
{
MessageBox.Show(ex.Message);
}
}
You can do this by catching the exception in the BeginInvoke function and saving it in a temporary variable. After the await you can then rethrow it on the correct thread.
Exception thrown = null;
await Application.Current.Dispatcher.BeginInvoke(new Action<Action>(x =>
{
try
{
BackGroundMethod();
}
catch (Exception ex)
{
//exceptions on this thread MUST be caught or the program will exit
//we will save it, and then when we are back on the main thread we will rethrow it
thrown = ex;
}
}));
if (thrown != null)
throw thrown; //<--- I'm rethrowing it right here on the correct thread
I have a scenario where a worker thread performs a task that looks like
try
{
for()
{
functionA();
functionB();
}
}
catch(Exception ex)
{
throw new Exception("Message");
}
I'm basically re-throwing the exception so that when the worker completes, the UI thread will receive the exception.
Now, if an exception occurs in functionA I'd like to throw the exception but continue the loop and not stop. How can I achieve this?
edit: If it isn't clear, this is so that the UI can be notified that an exception has occurred but not stop the worker
Something like this:
List<Exception> errorsLog = new List<Exception>();
for()
{
try
{
functionA();
}
catch(Exception e) {
errorsLog.Add(e);
}
try
{
functionB();
}
catch(Exception e) {
errorsLog.Add(e);
}
}
if (errorsLog.Count > 0) {
throw new AggregateException(errorsLog);
}
Where AggregateException is your custom exception that contains a list of other exceptions.