函数不断抛出索引超出范围异常

Function keeps throwing index out of range exception

我有一个函数可以根据传递的索引从列表中获取 IWebElement。

这里是 属性 -

public IList<IWebElement> ExistingDrafts { get { return Driver.FindElements(By.ClassName("broadcast-list-item")); } }

这里是函数-

public void DeleteDraft(int index = 0) {

     if(ExistingDrafts.Count > 0) {
        ExistingDrafts[index].Click();
     }

     IWebElement discardButton = Driver.FindElement(By.XPath("/html/body/div[2]/div/div[1]/div[2]/div/div[2]/form/div[7]")).FindElements(By.ClassName("form-control"))[0];
     Wait.Until(w => discardButton != null);

     discardButton.Click();
  }

这是我在测试中的使用方式-

[Fact]
  public void DeleteTheDraft() {

     BroadcastPage.DraftsHyperLink.Click();
     //delete first draft
     string firstDraftSubj = BroadcastPage.ExistingDrafts[0].Text;
     System.Threading.Thread.Sleep(6000);
     BroadcastPage.DeleteDraft(0);

     string newfirstDraftSubj = BroadcastPage.GetNewestDraftSubject();
     BroadcastPage.Wait.Until(w => newfirstDraftSubj != null);

     Assert.True(firstDraftSubj != newfirstDraftSubj, "Draft was not deleted");
  }

当我通过测试进行调试时,它通过了。但是,如果我 运行 测试,它会抛出异常。我不确定发生了什么。

发生这种情况是因为页面上并未加载所有元素。 基本上 public IList<IWebElement> ExistingDrafts { get { return Driver.FindElements(By.ClassName("broadcast-list-item")); } } 只会得到一些元素(看到你检查 Count > 0)。

最好的方法是在适当的位置等待,等待所有元素都出现,这可以通过使用以下方法实现:

public By ExistingDraftBy
{
    get {return By.ClassName("broadcast-list-item");}
}

WebDriverWait wait = new WebDriverWait(driver, new TimeSpan(0, 2, 0));
wait.Until(ExpectedConditions.PresenceOfAllElementsLocatedBy(ExistingDraftBy));

为了安全起见,请修改您的 if 语句以检查索引是否小于计数:

if(ExistingDrafts.Count > 0 && index < ExistingDrafts.Count) 
{
    ExistingDrafts[index].Click();
}