我使用 Selenium Webdriver a lot ,还有很多我写的“实用”方法让我更容易使用。我将这些类放在 WebDriverUtil
类中,现在该文件超过 1,200 行。 WebDriverUtil
中的每个方法都试图将我与 WebDriver
分开,因为我经常使用它而不是 DRY。继续写作。
例如,这是我将放入 WebDriverUtil
的方法。
public void waitUntilVisible(final WebElement webElement) {
new WebDriverWait(webDriver, 10).until(new Predicate<WebDriver>() {
@Override
public boolean apply(WebDriver webDriver) {
return webElement.isDisplayed();
}
});
}
如果我有 1,200 行充满这样方法的代码,我是否有 God object ?如果是这样,我该如何解决?
我应该像这样将我的行为分成装饰器类吗?
public class WebElementDecorator implements WebElement {
private WebElement webElement;
private final WebDriver webDriver;
public WebElementDecorator(WebElement webElement, WebDriver webDriver) {
this.webElement = webElement;
this.webDriver = webDriver;
}
public void waitUntilVisible() {
new WebDriverWait(webDriver, 10).until(new Predicate<WebDriver>() {
@Override
public boolean apply(WebDriver webDriver) {
return webElement.isDisplayed();
}
});
}
public void click() {
webElement.click();
}
//... other WebElement methods
}
最佳答案
If I have 1,200 lines of code full of methods like this, do I have a God object?
仅靠代码行数并不能充分说明一个类是否神似。由于糟糕的编码风格、过度工程、过度特化方法的不同变体、冗长的语言、内联注释等,一个类可能会因代码而变得臃肿。
上帝类是一个因职责而臃肿的类。这里有两个试金石来确定你的 util 类是否已经演变成一个 god 类:
更改测试时对 util 类的影响。如果对测试子集的更改导致您经常更改和重新编译您的 util 类,那么这可能表明您的 util 类服务于太多的主人。理想情况是,对测试子集的更改只会影响那些与测试直接相关的 util 方法(如果需要)。
更改实用程序类时对测试类的影响。如果更改您的 util 类的一部分导致许多不相关测试出现意外失败,那么您的 util 类可能已将其触角伸到您的所有测试中。
If so, how could I fix it? Should I separate my behavior into decorator classes like this?
最好从小的增量步骤开始重构。使用您的代码示例,我将从简单地将所有 Wait..Until..Predicate
代码提取到名为 WaitUntilEvent()
或其他名称的单独类中开始,方法如下 isVisible()
、isEnabled()
、isSelected()
等。示例用法如下所示:
WaitUntilEvent waitUntil = new WaitUntilEvent(webElement, webDriver);
waitUntil.isVisible();
webElement.click();
// etc..
如果我需要更改关于Wait..Until..Predicate
的测试要求(例如超时间隔),我知道只有一个类需要编辑。然后可以将其进一步重构为 until(PredicateIsTrue).then(PerformAction)
、until(FunctionIsTrue).then(PerformAction)
等。我比 all 更喜欢这种方法-包含神般的 class WebElementDecorator
,它可能会以许多装饰方法捕获许多不同的行为而告终。
关于java - <SomeThirdPartyClass>Util == 神对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32001009/