我目前正在进行网络测试,使用 WebDriver 来模拟浏览器。该 WebDriver 必须经常查找 HTML 元素,其中许多元素通常是相同的(即某个按钮、表单字段等)。 WebDriver 需要 Selenium 的 By
类的对象才能使用 findElement()
。
我认为,如果有一个枚举或接口(interface)存储By
的配置实例(可用于定位元素),那么它的可读性和适应性会很好。在测试中,重复硬编码 findElement(By.id("elementid"))
会变成 findElement(WebGui.Login.SUBMIT_BUTTON)
,其中 WebGui.Login.SUBMIT_BUTTON
可能会返回搜索 ID、名称、CSS 类等的 By
实例。无论需要什么,都不需要考虑只需要元素的测试本身。
Question A hierarchical structure seems optimal to represent different sections of the website, however enums can't inherit anything. Which way is the most clean way and/or best practice?
嵌套枚举由于枚举不能继承getBy()
和构造函数,因此必须在每个嵌套枚举中定义它们,因此代码更加冗余。
public enum WebGui {
BUTTON1(By.id("button1")),
SEND_BUTTON(By.name("sendButton"));
private By searchCriteria;
WebGui(By by) {
searchCriteria = by;
}
public By getBy() {
return searchCritera;
}
private enum SubPage {
BUTTON2(By.id("button2")),
SEND_BUTTON(By.linkText("Send"));
private By searchCriteria;
WebGui(By by) {
searchCriteria = by;
}
public By getBy() {
return searchCritera;
}
}
}
嵌套接口(interface)/抽象类使用这种方式似乎不太“干净”,不提供类型安全(尽管在这里不太相关),并且通常被称为不好的做法,因为存储一组固定的可用常量是枚举的目的。
编辑嵌套接口(interface)不能是私有(private)的,因此将外部接口(interface)
更改为抽象类
public abstract class WebGui {
By BUTTON1 = By.id("button1");
By SEND_BUTTON = By.name("sendButton");
private interface SubPage {
By BUTTON2 = By.id("button2");
By SEND_BUTTON = By.linkText("Send");
}
}
由于嵌套接口(interface)的代码要少得多,并且其成员不需要函数,因此使用它似乎是更好的选择,但与包含冗余代码的嵌套枚举相比,这是一种糟糕的做法。
最佳答案
您可以让枚举实现一个接口(interface),就像我对此的回答 question .
关于java - 分层存储常量的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45671024/