首页 > 解决方案 > 将 IWeb 元素从一个列表移动到另一个列表并使用 Selenium 比较它们的计数?

问题描述

目标是为 QA​​ 创建一个自动化测试,该测试通过使用 Selenium WebDriver 拥有的元素/项目的数量来断言一个 List 与另一个 List 不同。

这是获取列表的网页:http: //demoqa.com/sortable/然后连接列表

这是代码:

[Test]

//Arrange

_driver = new ChromeDriver(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
_driver.Navigate().GoToUrl("http://demoqa.com/sortable/"); 

List<IWebElement> sortableListOne = _driver.FindElements(By.Id("sortable1")).ToList();

IWebElement sortableListOneFifth = _driver.FindElement(By.XPath(@"//*[@id=""sortable1""]/li[5]"));

List<IWebElement> sortableListTwo = _driver.FindElements(By.Id("sortable2")).ToList();

IWebElement sortableListTwoForth = _driver.FindElement(By.XPath(@"//*[@id=""sortable2""]/li[4]"));

//Act

Actions action = new Actions(_driver);
            action.DragAndDrop(SortableListOneFifth, SortableListTwoForth)
                .Perform(); 

所以我尝试了:

//Assert
        var list1 = _sortPage.SortableListOne.Count;
        var list2 = _sortPage.SortableListTwo.Count;

        list1.Should().NotBe(list2);

错误信息:

Message: Did not expect list1 to be 1.

两个列表都返回 1 的计数,因此它们始终相同,并且不返回列表的 IWeb 元素。

我是否需要创建一个 for 循环来迭代每个列表?关于如何进行的想法?

标签: c#seleniumselenium-webdriverautomated-testsqa

解决方案


它看起来sortableListOnesortableListTwoWebElements 是使用 id 标识的,并且只找到一个匹配的元素,因此它返回为 1。

请使用下面的 xpath找到sortableListOne 和WebElementssortableListTwo

代码:

List<IWebElement> sortableListOne = _driver.FindElements(By.XPath("//ul[@id='sortable1']/li")).ToList();

List<IWebElement> sortableListTwo = _driver.FindElements(By.XPath("//ul[@id='sortable2']/li")).ToList();

更改 sortableListOne andsortableListTwo` 元素定位器后,请在您的测试方法中使用以下内容,它将返回正确的计数

var list1 = _sortPage.SortableListOne.Count;
var list2 = _sortPage.SortableListTwo.Count;

list1.Should().NotBe(list2);

推荐阅读