【问题标题】:Is there a cleaner way to write this polling loop?有没有更简洁的方法来编写这个轮询循环?
【发布时间】:2012-11-02 15:16:15
【问题描述】:

我正在用 Java 中的 Selenium/WebDriver 编写自动化测试用例。我实现了以下代码来轮询现有的 WebElement,但由于我不是 Java 专家,我想知道是否有更简洁的方法来编写此方法:

/** selects Business index type from add split button */
    protected void selectBusinessLink() throws Exception
    {
        Calendar rightNow = Calendar.getInstance();
        Calendar stopPolling = rightNow;
        stopPolling.add(Calendar.SECOND, 30);
        WebElement businessLink = null;
        while (!Calendar.getInstance().after(stopPolling))
        {
            try
            {
                businessLink = findElementByLinkText("Business");
                businessLink.click();
                break;
            }
            catch (StaleElementReferenceException e)
            {
                Thread.sleep(100);
            }
            catch (NoSuchElementException e)
            {
                Thread.sleep(100);
            }
            catch (ElementNotVisibleException e)
            {
                Thread.sleep(100);
            }
        }
        if (businessLink == null)
        {
            throw new SystemException("Could not find Business Link");
        }
    }

这一行让我觉得代码有点脏:

 while (!Calendar.getInstance().after(stopPolling))

【问题讨论】:

  • 只是一个注释。 java.util.Calendar 是一个糟糕的接口和实现。如果可以,请改用 JodaTime,或直接使用 longs 作为毫秒。

标签: java loops webdriver polling selenium-webdriver


【解决方案1】:

你可以这样做

long t = System.currentMillis();   // actual time in milliseconds from Jan 1st 1970.
while (t > System.currentMillis() - 30000 )  {
   ...

【讨论】:

  • ,但这正是我想要的。非常感谢。
【解决方案2】:

以毫秒为单位的系统时间怎么样?

Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.SECOND, 30);
long stopPollingTime = calendar.getTimeInMillis();
while (System.currentTimeMillis() < stopPollingTime) {
  System.out.println("Polling");
  try {
    Thread.sleep(100);
  } catch (InterruptedException e) {
  }
}

【讨论】:

    猜你喜欢
    • 2012-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多