Question

Can anyone please help me with the following scenarios I want to use with if/else conditions. I'm using java with Testng Eclipse.

1) If login is successful and navigates you to Home page, avoid try/catch 2) If login fails, go to try block.

        driver.findElement(By.name("username")).sendKeys(username);
        driver.findElement(By.name("password")).sendKeys(password);
        driver.findElement(By.name("login")).submit();

      try{

        Assert.assertFalse(driver.findElement(By.xpath("//div[@class='errorMsg']")).getText().matches("Username or password incorrect. Try again."));
        }
        catch(Throwable t){
            Assert.fail("Username Or Password is Incorrect.");
        }
        Assert.assertEquals(actualTitle, title,"Home is not accessible!");
Was it helpful?

Solution

It'd be as simple as replacing the try-catch with an if, but since findBy will throw exception if no element is found, you have at least the following 2 approaches

1) create a reusable findElementIfPresent method which returns null if no element is found:

    private WebElement findElementIfPresent(WebDriver driver, By by){
        try {
            return driver.findElement(by);
        } catch (NoSuchElementException e) {
            return null;
        }
    }

    ...

    driver.findElement(By.name("username")).sendKeys(username);
    driver.findElement(By.name("password")).sendKeys(password);
    driver.findElement(By.name("login")).submit();

    // obtain the div which holds the information
    WebElement errorDiv = findElementIfPresent(driver, By.xpath("//div[@class='errorMsg']"));


    // if the div exists and it has an authentication-problem messages, fail
    if(errorDiv != null && errorDiv.getText().matches("Username or password incorrect. Try again."))
        fail("Username Or Password is Incorrect.");
    }

    // otherwise proceed with additional verifications
    assertEquals(actualTitle, title,"Home is not accessible!");

2) go with the javadoc's suggestion and use findElements(By) which returns a list of elements. In your particular case, if the list is empty then the authentication was successful, otherwise fail the test

    // obtain the list of error divs
    List<WebElement> errorDivs = driver.findElements(By.xpath("//div[@class='errorMsg']"));

    // if there is at east one element present
    if(!errorDivs.isEmpty()){
        // pick first one and use as main failure reason
        fail(errorDivs.get(0).getText());
    }

    // otherwise proceed with additional verifications
    assertEquals(actualTitle, title,"Home is not accessible!");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top