我在我的 SUT 中使用了类似的方法,因为它适用于相当复杂的对象,包括在测试执行期间预先创建和动态生成的 - 并且它们的主要用户可识别属性是显示的名称。这是我的流程的简化版本,它基于字符串替换。
从变量文件开始——一个简单的 selenium 定位器集合,定位器的值有一个“特殊”字符串,稍后将被替换:
*** VARIABLES ***
${DROPDOWN ITEMS} xpath=//*[contains(@class,'listitem-element')]/span[contains(text(),'SELENIUM_PLACEHOLDER_CHANGE_ME')]
然后,在关键字文件中有用于返回正确定位器的私有关键字,例如这个:
*** KEYWORDS ***
_Return Selenium Locator For The Dropdown Item Named
[Documentation] Verifies the desired dropdown item is valid, ando returns its locator (not Webelements!!)
[Arguments] ${name}
# change the placeholder with the actual UI name
${loc}= Replace String ${DROPDOWN ITEMS} SELENIUM_PLACEHOLDER_CHANGE_ME ${name}
# why? Rationale explained below
Element Should Be Visible ${loc} message=The dropdown does not have an item called ${name}
[Return] ${loc}
为什么要进行能见度检查?简单 - 如果 SUT 中当前没有这样的对象,则尽早失败,并具有统一的错误消息,与元素如何进一步使用无关(单击、检查存在、属性检索等)
然后,用于对元素执行操作的后续用户关键字使用前一个:
# the user keywords
Choose Value From Dropdown
[Documentation] It does what it does :)
[Arguments] ${the value}
${loc}= _Return Selenium Locator For The Dropdown Item Named ${the value}
# as you can see, no checks is the element real - that'she offloaded to the helper keyword ^
Focus Element ${loc}
Click Element ${loc}
最后,测试用例使用关键字来处理您认为需要的任何数据:
*** TESTCASE ***
The dropdown should do X
[Documentation] Steps: 1, 2, 3, etc
# do the normal steps you'do do
Choose Value From Dropdown my current value
这种方法也适用于负面测试 - 例如,要检查值不存在,测试用例将包含:
Run Keyword And Expect Error The dropdown does not have an item called no_such_element Choose Value From Dropdown no_such_element
因此,我们都使用 selenium 检查元素的缺失,并保持测试用例接近现实生活中的表达——对应该发生的事情的描述,没有特殊的语法和 SE 关键字。
请原谅任何拼写错误和轻微的语法遗漏 - 在手机上打字并不容易,下次我会三思而后行:D