java - 分层存储常量的最佳实践

标签 java enums interface

我目前正在进行网络测试,使用 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/

相关文章:

c# - 尽管有一个方法,但没有找到合适的方法来覆盖 c#?

c# - 继承 ICollection<T> 的抽象基类

c++ - 如何将这个工厂逻辑保存在一个地方?

java - 如何修复 RN 中的 `cannot be cast to java.lang.String`?

iOS 枚举、类和按钮、方法

performance - 为什么 Python 枚举很慢?

c# - 将不同的枚举组合成一个参数 C#

java - C++ std::string 到固定长度的 jstring

java - 使用反射代替长 switch 语句

java - 我收到 "java.lang.ClassNotFoundException: com.google.gson.Gson"错误,即使它是在我的类路径中定义的