问题描述
我目前正在为 UI 测试自动化的元素放置一些 ID.这些 ID 仅用于测试.我应该添加数据属性而不是可能使其对未来的开发人员更具可读性(data-testHandle="mybutton")还是应该坚持使用 ID.
I'm currently placing some ID's on elements for UI Test automation. These ID's are only being used for testing. Should I be adding data-attributes instead possibly making it more readable to future developers(data-testHandle="mybutton") or should I stick with ID's.
w3.org 说:
自定义数据属性旨在存储私有的自定义数据没有更合适的页面或应用程序属性或元素.
Custom data attributes are intended to store custom data private to the page or application, for which there are no more appropriate attributes or elements.
我倾向于保留 ID,但我的某些部分认为未来的开发人员会认为 ID 未被使用并删除它们.
I'm leaning towards keeping ids but some part of me thinks that future developers would think the ID's aren't used and remove them.
这里有任何最佳实践.谢谢.
Any best practices here. Thanks.
推荐答案
这接近于基于意见,这里是有助于做出选择的总结.
This is close to being opinion-based, by here is the summary that should help to make a choice.
为什么要使用 ID
属性:
Why would you use an ID
attribute:
- 这是一种常见的,并且是每个从事自动化测试的人都熟悉的定位元素的方法
- 这通常是在页面上定位元素的最快方法,因为 selenium 可以将其归结为执行现代浏览器优化的
document.getElementById()
(尽管,通常端到端 UI 测试的性能并不重要) - 它是每个 selenium 语言绑定中的内置定位器
- 如果您使用 Firebug 或 Chrome 开发工具 - CSS 选择器和 XPath 生成工具通常会尽可能使用元素的
id
提供更强大的定位器 - 您将构建更短的 CSS 选择器和 XPath 表达式.例如.
#myid .someclass
而不是[automation-id=myid] .someclass
.
- this is a common and familiar to everybody doing test automation way to locate elements
- this is generally the fastest way to locate elements on a page because selenium gets it down to executing
document.getElementById()
which is optimized by the modern browsers (though, usually performance of the end-to-end UI tests is not critical) - it is a built-in locator in every selenium language binding
- if you would use Firebug or Chrome Developer Tools - the CSS selector and XPath generation tools would generally provide more robust locators using the
id
s of the element whenever possible - you would build shorter CSS selectors and XPath expressions. E.g.
#myid .someclass
as opposed to[automation-id=myid] .someclass
.
为什么要使用自定义属性:
- 如果您要向所有需要的元素添加,例如,
automation-id
属性,您会在某种程度上将其命名空间/范围用于测试自动化 - 每个人都会从属性中知道这是什么名称.这意味着,与id
属性相比,您将大大减少开发人员故意更改属性的机会,该属性也可以并且通常也用于应用程序客户端逻辑(参考 this 和 this 答案)
- if you would add, say,
automation-id
attributes to all the desired elements, you would somewhat namespace/scope it to the test automation - everybody would know what is this for just from the attribute name. Meaning, you would dramatically decrease chances of a developer changing the attribute intentionally as opposed to anid
attribute, which can and is usually used for application client-side logic as well (reference to this and this answer)
另外,这里有一些相关的主题:
Also, here are some relevant threads:
- 正在为所有标准实践添加 ID何时使用 Selenium?
- 使用 webdriver 查找元素的最佳和最快方法是什么?By.XPath 或 By.ID 还是其他?为什么?
- 比用于识别 Selenium 测试中的元素的 ID
这篇关于测试自动化 html 元素选择器.元素 ID 或 DataAttribute的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!