Selenium等待逻辑

时间:2016-12-21 13:48:24

标签: c# selenium selenium-webdriver coded-ui-tests

我正在为我的网站构建测试框架 我想完全将框架从测试中分离出来 问题是当我编写测试时有时Assert需要时间直到它可以成为现实,例如,如果我在上传文件页面上,当文件上传时,网站应该显示文件上传成功页面,但它需要很长时间,直到浏览器到达此页面

我应该如何强制Assert在返回结果之前等待一段时间?

可能解释我当前工作方式的一些代码:

上传页面类

Public class UploadPage
{
 [FindsBy(How = How.Name, Using = "upload-button")]
 public IWebElement BtnUpload { get; set; }

  public UploadPage()
  {
   PageFactory.InitElements(Driver, this);
  }

 public void UploadFile(string path)
  {
    //select file
    BtnUpload.Click();
  }
}

成功上传页面:

 Public class UploadSuccessfulPage
   {
     [FindsBy(How = How.Name, Using = "success-message")]
     public IWebElement LblSuccessMessage{ get; set; }

     public UploadSuccessfulPage()
     {
       PageFactory.InitElements(Driver, this);
     }
     public bool IsAt()
     {
      Driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(60))
      return Driver.url==configurations.UploadSuccessfulPageURL;
     }
   } 

测试方法:

public void TestUpload()
{
 UploadPage uploadPage= new UploadPage ();
 uploadPage.UploadFile(path);
 UploadSuccessfulPage successPage= new UploadSuccessfulPage();
 Assert.IsTrue(successPage.IsAt());
}

当我以这种方式编写测试时,尽管IsAt()包含隐式等待,但断言不会等待

P.S:我不打算使用Thread.Sleep();

1 个答案:

答案 0 :(得分:2)

方法bool IsAt()应该像:

一样实现
public bool IsAt()
{
  Driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(60));
  try {
     return driver.FindElement(By.Name("success-message").Displayed;
  } catch (WebDriverException e) {
    return false;
  }
}

或使用显式等待:

public bool IsAt()
{
  try {
    WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(60));
     wait.Until(ExpectedConditions.ElementIsVisible(By.Name("success-message")));
    return true;
  } catch (TimeoutException e){
    return false;
  }
}

<强>更新: 如果您想通过网址验证,bool IsAt()应如下所示:

public bool IsAt()
    {
      try {
        WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(60));
         wait.Until(ExpectedConditions.UrlToBe(configurations.UploadSuccessfulPageURL));
        return true;
      } catch (TimeoutException e){
        return false;
      }
    }

查看班级ExpectedConditions以找到适合您要求的条件