Reputation: 27320
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?
Upvotes: 2
Views: 4619
Reputation: 1487
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
Upvotes: 2
Reputation: 27320
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.
Upvotes: 3
Reputation: 1210
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')
}
Upvotes: 0
Reputation: 22710
Java equivalent will be
public boolean isElementExists(By by) {
boolean isExists = true;
try {
driver.findElement(by);
} catch (NoSuchElementException e) {
isExists = false;
}
return isExists;
}
Upvotes: 0