【问题标题】:PHPUnit + Selenium test if a div has a css classPHPUnit + Selenium 测试一个 div 是否有一个 CSS 类
【发布时间】:2014-07-23 23:50:16
【问题描述】:

问题

如何使用 PHPUnit 和 Selenium 检查 div 是否具有特定的 css 类或其他属性?

背景

我一直在使用 PHPUnit 和 Selenium 在多个站点上执行功能测试。测试目前正在扩展 PHPUnit_Extensions_SeleniumTestCase 但如果它会提供更好的解决方案,我使用 PHPUnit_Extensions_Selenium2TestCase 没有问题。

测试示例

这是一个测试示例,实际使用要复杂得多,测试类被抽象为几个子类,我的测试用例扩展了这些子类。

在这个例子中,我希望能够点击一个按钮 (some_button) 并检查一个 div (some_div) 是否有 css 类“活动”。

class ExampleTest extends PHPUnit_Extensions_SeleniumTestCase {

protected $captureScreenshotOnFailure = true;

    public function setUp() {

        //Load some base application configuration and set $base_url

        $this->setBrowser('firefox');
        $this->setBrowserUrl($base_url);
    }

    public function testIfButtonChangesClass() {
        $this->open("/test_page");

        $this->select("id=some_combo", "value=2");
        $this->assertFalse($this->isVisible('id=some_button'));

        $this->click("id=some_button");

        //How do I test if some_div has the class active? it would be nice to do 
        //something like this?
        $this->assertTrue($this->hasClass('id=some_div','active'));

        }

    }


}

【问题讨论】:

  • 956 次观看,只有 1 次点赞,这些天我很担心这个社区。​​span>

标签: php selenium phpunit


【解决方案1】:

最简单的方法就是断言所需类的存在。例如,假设您有一些带有 id 的 div:

<div id="mydiv">blah</div>

当您单击按钮时,您有一些 Javascript 会从 div 中添加“someclass”类:

$this->click("id=mybutton"); // this click should add the class

// now test to see if the class has been added
$this->assertElementPresent("css=div#mydiv.someclass");

div#mydiv 将以一种或另一种方式存在。 div#mydiv.someclass 只有在添加了 someclass 类时才会存在。

请注意,我的断言语法与您的略有不同——我使用的是一步法assertElementPresentPHPUnit_Extensions_SeleniumTestCase 类公开了一大堆有用的断言,这些断言与 Selenium 文档中的断言相匹配。

【讨论】:

  • 这些有用的断言风格方法在 v2 中消失了,看来您必须只选择元素(使用 byName 或类似元素)然后捕获异常?如果我弄清楚规范形式,我会发布第二个答案......
【解决方案2】:

在带有PHPUnit_Extensions_Selenium2TestCase 语法的 Selenium 2 中,更鼓励您使用 PHPUnit 标准断言,并且只使用 selenium 来访问页面元素(而不是在 v1 中混合使用两者)。

你可以这样做:

$element = $this->byId('some_div');
$this->assertContains('active', $element->attribute('class'));

或类似于 Kryten 的回答,您可以尝试“获取”元素并让它失败或处理异常以转换为失败甚至继续:

try{
    $element = $this->byByCSSSelector('div#some_div.active');
} 
catch(PHPUnit_Extensions_Selenium2TestCase_WebDriverException $e) {        
    $this->fail('Class "active" not found. '.$e->getMessage());
}

我个人更喜欢第一种方法。

【讨论】:

    猜你喜欢
    • 2013-10-19
    • 2011-05-26
    • 2017-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-29
    • 1970-01-01
    相关资源
    最近更新 更多