我正在尝试使用一个Enum来设置一个可能的距离的有限列表,该字符串被用作Selenium API方法中的cssSelector:
public enum DistanceFrom {
FIVEMILES("a[data-reactid='.2cr8yg16ohc.2.1.0.2:$5.0']"),
TENMILES("a['.2cr8yg16ohc.2.1.0.2:$10.0.2']"),
TWENTYMILES("a['.2cr8yg16ohc.2.1.0.2:$20.0']"),
THIRTYMILES("a['.2cr8yg16ohc.2.1.0.2:$30.0']");
private String value;
DistanceFrom(String value){
this.value=value;
}
@Override
public String toString(){
return value;
}
}
我在测试中使用它:
local.setDistance(DistanceFrom.FIVEMILES.toString());
其中setDistance是页面对象中的一种流畅方法:
public LocalNewsPage setDistance(String value) {
WebElement setDistanceButton = driver.findElement(By.cssSelector(value));
setDistanceButton.click();
return this;
}
为什么我必须声明:
local.setDistance(DistanceFrom.FIVEMILES.toString());
而且不能简单地:
local.setDistance(DistanceFrom.FIVEMILES);
最佳答案
如果可以编辑setDistance
方法,则可以将其更改为接受DistanceFrom
:
public LocalNewsPage setDistance(DistanceFrom value) {
WebElement setDistanceButton = driver.findElement(By.cssSelector(value.toString()));
setDistanceButton.click();
return this;
}
或者,您可以将
DistanceFrom
中的枚举值更改为static final String
s:public final class DistanceFrom {
public static final String FIVEMILES = "a[data-reactid='.2cr8yg16ohc.2.1.0.2:$5.0']";
public static final String TENMILES = "a['.2cr8yg16ohc.2.1.0.2:$10.0.2']";
public static final String TWENTYMILES = "a['.2cr8yg16ohc.2.1.0.2:$20.0']";
public static final String THIRTYMILES = "a['.2cr8yg16ohc.2.1.0.2:$30.0']";
private DistanceFrom() {}
}