我需要根据它包含的值点击元素..但我想在测试运行或关键字定义中设置这个值(我猜最好的选择是在测试中) 我应该怎么做?
包含 xpath 的变量应该是这样的:
${DROPDOWN ITEMS} xpath=//*[contains(@class,'listitem-element')]/span[contains(text(),'${second_number}')]
当我用像“002”这样的实际数字替换变量时,这个定位器工作,但我想让它更通用..
在关键字定义中,我这样使用它:
Choose Value From Dropdown
focus ${DROPDOWN ITEMS}
click element ${DROPDOWN ITEMS}
在测试中我只调用关键字
我的问题是在何处以及如何设置 xpath 中使用的 ${second_number} 变量的变量值? PS:xpath 定义、关键字和测试都在单独的文件中 谢谢!
最佳答案
我在我的 SUT 中使用了类似的方法,因为它处理相当复杂的对象,这些对象在测试执行期间预先创建和动态生成 - 并且它们的主要用户可识别属性是显示的名称。这是我的流程的简化版本,它基于字符串替换。
从变量文件开始 - 一个简单的 selenium 定位器集合,定位器的值有一个“特殊”字符串,稍后将被替换:
*** VARIABLES ***
${DROPDOWN ITEMS} xpath=//*[contains(@class,'listitem-element')]/span[contains(text(),'SELENIUM_PLACEHOLDER_CHANGE_ME')]
然后,在关键字文件中有用于返回正确定位器的私有(private)关键字,例如这个:
*** 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
关于selenium - 如何在XPATH中使用变量,应该在关键字或测试中设置哪个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40973598/