如何在Robot Framework中循环验证页面多文本并优化重复代码?
改造Robot Framework重复检查逻辑的两种方案
你可以通过列表循环或者封装独立关键字两种方式简化重复代码,具体实现如下:
方案一:用列表存储待检查文本,循环遍历处理
把要检查的文本A、B、C放到列表里,通过循环动态生成XPath并执行检查,避免重复编写相同逻辑:
Test Keyword # 定义待检查的文本列表 @{texts} Create List A B C # 遍历列表中的每个文本 :FOR ${text} IN @{texts} \ ${status}= Run Keyword And Return Status Page Should Contain Element xpath=//*[contains(text(), "${text}")] \ Run Keyword If ${status} Log To Console "(${text}) Present" ELSE Log To Console "(${text}) Not Present"
后续要新增检查文本时,直接在@{texts}列表里添加即可,无需修改循环逻辑。
方案二:封装独立关键字复用逻辑
把单个文本的检查逻辑封装成独立关键字,之后可以在任意用例中重复调用:
第一步:定义检查关键字
Check Text Presence [Arguments] ${target_text} ${status}= Run Keyword And Return Status Page Should Contain Element xpath=//*[contains(text(), "${target_text}")] Run Keyword If ${status} Log To Console "(${target_text}) Present" ELSE Log To Console "(${target_text}) Not Present"
第二步:在测试用例中调用
可以单独调用每个文本:
Test Keyword Check Text Presence A Check Text Presence B Check Text Presence C
也可以结合列表循环批量调用:
Test Keyword @{texts} Create List A B C :FOR ${text} IN @{texts} \ Check Text Presence ${text}
这种方式的优势是逻辑复用性更强,多个测试用例需要做类似文本检查时,直接调用关键字即可,后期修改检查逻辑也只需改动一处。
内容的提问来源于stack exchange,提问作者Justin Hooks
相关产品推荐
相关产品推荐

