遍历 IWebElements 元素并与 IList 字符串进行比较

Looping through IWebElements elements and comparing with IList string

我的DOM个元素:

<ul id="testList" class="sc-ksdxgE jiDfgt" xpath="1">
  <li class="sc-hBUSln fPSRnx">Carp and its Derivatives</li>
  <li class="sc-hBUSln fPSRnx">Tilapia and its Derivatives</li></ul>

我想要实现的是:

a)获取主元素(testList)或获取主元素元素的(li)

private readonly string allergensDoesContainListLocator = "//ul[@id = 'testList']//li";
public IList<IWebElement> AllergensDoesContainList => driver.FindElements(By.XPath(allergensDoesContainListLocator));

b) 创建我要传递和断言的元素列表:

IList<string> DoesContainAllergens => new List<string>(new string[] { "Carp and its Derivatives", "Tilapia and its Derivatives" });

c) 编写正确的循环方法 我在考虑简单的 LINQ,例如:

AllergensDoesContainList.Where(c => c.Text == allergensToCheck)

或 ForEach 语句

          //allergensToCheck.ForEach(delegate (string name)
                  //{
                  //    bool isAllergenVisible = driver.IsElementVisible(By.XPath(string.Format("//div[@data-automation='sizePanel[{0}]'][contains(.,'{1}')]", sizeIndex, name)));
                  //});

有人可以告诉我什么是完美的方法吗?如果有帮助,请将 NUnit 用于单元测试提供程序。

这涉及两个主要步骤。首先,将所有文本收集到一个 IEnumerable<string> 中。接下来,使用 NUnit 中的 CollectionAssert class 进行断言:

private readonly string allergensDoesContainListLocator = "//ul[@id = 'testList']//li";
private IList<IWebElement> AllergensDoesContainElements => driver.FindElements(By.XPath(allergensDoesContainListLocator));

private IEnumerable<string> AllergensDoesContainList => AllergensDoesContainElements.Select(element => element.Text);

现在你可以下结论了:

var expectedAllergens = new string[]
{
    "Carp and its Derivatives",
    "Tilapia and its Derivatives"
};

// If the order on screen matters to your assertion:
CollectionAssert.AreEqual(expectedAllergens, AllergensDoesContainList);

// If the order on screen does not matter:
CollectionAssert.AreEquivalent(expectedAllergens, AllergensDoesContainList);