首页 > 解决方案 > Selenium isSelected() 方法在说谎

问题描述

我正在尝试用硒测试一组单选按钮。我已将它们分组在一个列表中

@FindBy(xpath = "//ux-button-group//input[@name='options']") 
private List<WebElement> granularity;

当我测试第一个选项被选中时,它返回 me false

assertTrue(granularity.get(0).isSelected(), "Granularity should have selected the first option");

我已经调试并看到如果我尝试使用最后一个元素(3),那么它会给我true. 您可能会像我一样认为列表中的顺序以某种方式颠倒了,但事实并非如此。我通过检索列表中每个元素的 id 进行了检查,它们的顺序正确。我也尝试过检索“checked”属性,但这是错误的。前 3 个按钮返回null,最后一个按钮返回true

html:

<div data-toggle="buttons" class="ux-button-group btn-group  btn-lg" data-e2e="ux-button-group">
    <!----><!---->
    <label class="btn btn-primary btn-lg ng-star-inserted active">
        <input autocomplete="off" name="options" type="radio" id="shared.granularity.0" checked="true"> Daily <!---->
    </label>
    <label class="btn btn-primary btn-lg ng-star-inserted">
        <input autocomplete="off" name="options" type="radio" id="shared.granularity.1" checked="false"> Weekly <!---->
    </label>
    <label class="btn btn-primary btn-lg ng-star-inserted">
        <input autocomplete="off" name="options" type="radio" id="shared.granularity.2" checked="false"> Monthly <!---->
    </label>
    <label class="btn btn-primary btn-lg ng-star-inserted">
        <input autocomplete="off" name="options" type="radio" id="shared.granularity.3" checked="false"> Yearly <!---->
    </label>
    <!----><!---->
</div>

标签: javaselenium

解决方案


嗯,xpath 似乎不正确,ux-button-group应该是这样使用它的标签。

xpath 应该是:
//div[contains(@class, 'ux-button-group')]//input[@name='options']

或更简单的css:
.ux-button-group input[name=options]

或其他 css(更好,因为您可以从 id 名称中看到代表的内容):
input[id*='shared.granularity']

如果可能并且没有任何限制,也可以尝试 selenium 3.141.59。


推荐阅读