'Java Selenium register and handle unexpected notification element

In an effort to make my test project more robust, I'm trying to deal with an issue where an unexpected notification element on the page messes with my interactions. When doing certain actions on the page, a small (400x64) notification element will appear on the bottom right of the screen. If the action was successful, the notification will be green and say something like 'Success!'; if unsuccessful, the notification is red and contains a short description of what went wrong. Most of the time I know when to expect it, and I have a method in place that waits for it and relays the contents to the user. However, sometimes it appears unexpectedly and this almost always interferes with my interaction with the page. For example, it will appear on top of a button or input, which throws ElementClickInterceptedException.

So far, I have a separate class ErrorListener that implements Runnable, with the following method:

@Override
public void run() {
    while (!isError) {
        try {
            WebElement notification = driver.findElement(By.tagName("simple-notification"));
            if (notification.isDisplayed()) {
                if (notification.findElement(By.cssSelector(">div")).getAttribute("class").contains("error")) {
                    isError = true;
                    Assert.fail(notification.findElement(By.cssSelector("div.sn-content")).getText());
                }
            }
        } catch (NoSuchElementException e) {
            Thread.sleep(50);
        }
    }
}

This method continually waits for the notification, and fails the test with the contents of the notification if it is an error notification. In the @BeforeTest method I then create a new thread with a new instance of ErrorListener and run it:

new Thread(new ErrorListener()).start();

I have tested this, and it does catch the error notification and print out its contents, but the test continues instead of Assert.fail(). What am I doing wrong?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source