Question

I'm new to PHPUnit and Selenium, and I want to test a 'remove' button by confirming that an element with a given ID exists before the button is clicked, but no longer exists after the button is clicked.

If I use something like this to check that the element has been deleted:

$this->assertFalse($this->byId('idRemoved'));

Then I get a test failure in byId() because it can't find idRemoved (which is true, because it's not there.)

How can I test for the lack of an element, so the test fails if idRemoved is found?

Was it helpful?

Solution 3

Java equivalent will be

   public boolean isElementExists(By by) {
        boolean isExists = true;
        try {
            driver.findElement(by);
        } catch (NoSuchElementException e) {
            isExists = false;
        }
        return isExists;
    }

OTHER TIPS

This is what I ended up using, thanks to Karna's suggestion. I'm posting it as another answer as I am using PHP, so for the benefit of anyone else using PHPUnit and Selenium, here is a similar method to Karna's, but for PHPUnit:

try {
    $this->byId('idRemoved');
    $this->fail('The element was not deleted.');
} catch (PHPUnit_Extensions_Selenium2TestCase_WebDriverException $e) {
    $this->assertEquals(PHPUnit_Extensions_Selenium2TestCase_WebDriverException::NoSuchElement, $e->getCode());
}

The code was taken from line 1070 in the PHPUnit Selenium test code, which I found after Karna pointed me in the right direction.

For those arriving late at the party: a better solution would be to create your own expected condition class and extend the Facebook\WebDriver\WebDriverExpectedCondition to write your own method:

public function elementNotPresent(WebDriverBy $by)
{
    return new static(
        function (WebDriver $driver) use ($by) {
            try {
                $driver->findElement($by);
                return false;
            } catch (Exception $e) {
                return true;
            }
        }
    );
}

Update: The above is intended for Facebook's Selenium WebDriver bindings for PHP

You can assert that a specific exception gets thrown if you'd like:

/**
 * @expectedException        MyException
 * @expectedExceptionMessage Some Message
 */
public function testExceptionHasRightMessage()
{
    //yourCodeThatThrows new MyException('Some Message')
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top