Selenium: How to assert a WebElement that doesn’t exist

Just in case you need to assert that a WebElement doesn’t exist, here’s a code snippet that you can use.

Java

public int isElementPresent(String xpath) {
    return  driver.findElements(By.xpath(xpath)).size();
}

Cucumber
@Then("^I expect to see the link On the page$")
public void iExpectToSeeTheLinkOnThePage() {
    assertTrue(demoPage.isElementPresent() > 1);
}

Java code snippet: Enumeration to return String value

I probably should be adding this kind of stuff on GitHub, but I’m lazy. 🙂


public enum TokenType {

    TICKET("ticket"),
    UNKNOWN("unknown");

    private String tokenType;

    TokenType(String tokenType) {
        this.tokenType = tokenType;
    }

    public String getTokenType() {
        return tokenType;
    }

    public boolean isTicket() {
        return this == TICKET;
    }

    public boolean isValidType() {
        return this == TICKET;
    }

    public static TokenType getByTokenType(String tokenType) {
        String safeTokenType = (tokenType != null) ? tokenType.toLowerCase().trim() : "";

        for (TokenType tt : values()) {
            if (tt.getTokenType().equals(safeTokenType)) {
                return tt;
            }
        }

        return UNKNOWN;
    }

    public boolean isUnknown() {
        return this == UNKNOWN;
    }
}