Bhupendra Singh Rautela
Bhupendra Singh Rautela

Reputation: 3606

Selenium test case is getting pass in every case either the element present on page or not

My selenium test case is given below:

@Test(priority = 1)
public void Check_Funnel_on_homepage() throws Exception {
    try {
        isElementDisplayed((By.id(propObjctRepo.getProperty("xpath_abc"))));
    } catch (Exception e) {
        addErrorlogs(e, "Error message");
    }
}

My test method is given below:

@SuppressWarnings("deprecation")
public boolean isElementDisplayed(By element) throws Exception {
    try {
        Assert.assertTrue(dvr.findElement(element).isDisplayed());
        addlogs("Element " + element + " found on page");
        System.out.println("Element " + element + " found on page");
        return true;
    } catch (AssertionError e) {
        System.out.println("Element " + element + " not found on page");
        return false;
    } catch (Exception e) {
        System.out.println("Element " + element + " not found on page");
        return false;
    }
}

I am facing an issue, In every case either the element present on page or not the test case is returning true and passing in testNG report.

Upvotes: 0

Views: 494

Answers (2)

Guy
Guy

Reputation: 51009

You don't do anything if isElementDisplayed() return false, you need to use assert

public void checkFunnelOnHomepage() {
    By by = By.id(propObjctRepo.getProperty("xpath_abc"));
    boolean isDisplayed = isElementDisplayed(by);
    Assert.assertTrue(isDisplayed, "Element " + by + " not found on page");
}

You can add the assertion message to assertTrue(), and change isElementDisplayed(By element) to only return true or false

public boolean isElementDisplayed(By by) {
    List<WebElement> elements = dvr.findElements(by);
    return elements.size() > 0 && elements.get(0).isDisplayed();
}

If you use findElements you avoid using try catch. It is also the recommended way

findElement should not be used to look for non-present elements, use WebDriver.findElements(By)

Be careful using try catch, it will ignore the assertion error.

As a side note, according to Java naming conventions Check_Funnel_on_homepage should be checkFunnelOnHomepage.

Upvotes: 3

Milind Auti
Milind Auti

Reputation: 11

this is because you are catching the assertion error and returning false. and doing nothing with the returned value. hence end result for your test is test case is passed

Upvotes: 1

Related Questions