Selenium 等待逻辑

Selenium Waits Logic

我正在为我的网站构建一个测试框架 我想将框架与测试完全分开 问题是当我编写测试时,有时 Assert 需要时间才能为真,例如,如果我在上传文件页面上,并且当文件上传时,网站应该显示文件上传成功页面,但它需要很多时间直到浏览器到达此页面

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

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

上传页面Class

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();

方法 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;
  }
}

更新: 如果你想通过 url 验证,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;
      }
    }

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