如何在Robot Framework(SeleniumLibrary)测试用例中实现关键字单次与多次执行
1. Running a Specific Keyword Multiple Times
There are a couple of straightforward ways to handle this, depending on whether you need consistent parameters or variable input each run:
Option A: Fixed Runs with Same Parameters
If you just need to execute the keyword a set number of times using the same arguments, use Robot Framework's built-in Repeat Keyword from the BuiltIn library. Example:
*** Test Cases *** Repeat Keyword With Fixed Params Repeat Keyword 3 times KEYWORD1 userid@mysite.com mypass CONTENT A
This will run KEYWORD1 three times in sequence, using the exact same credentials and content each time.
Option B: Variable Runs with Different Data
For scenarios where you need to pass different values each time (like your example with CONTENT A/B/C), Test Templates are ideal. Your existing snippet is already on the right track—here's a refined version:
*** Settings *** Test Setup OPEN CHROME BROWSER Test Teardown CLOSE CHROME BROWSER Test Template KEYWORD1 Force Tags Smoke *** Test Cases *** VALID CREDENTIAL WITH MULTIPLE CONTENTS userid@mysite.com mypass CONTENT A userid@mysite.com mypass CONTENT B userid@mysite.com mypass CONTENT C *** Keywords *** KEYWORD1 [Arguments] ${userid} ${userpass} ${content} # Example keyword logic Input Text id=username ${userid} Input Text id=password ${userpass} Click Button id=submit Input Text id=content-field ${content} Click Button id=save-content
Each row under the test case name acts as a parameter set for KEYWORD1, so it will run three times total—once per content value.
2. Executing One Keyword Once + Another Multiple Times
To mix one-time and repeated actions in a single test case, structure your test to run the one-time keyword first, then loop through the repeated keyword using a FOR loop. Here's a practical implementation:
*** Settings *** Test Setup OPEN CHROME BROWSER Test Teardown CLOSE CHROME BROWSER Force Tags Smoke *** Test Cases *** Mix One-Time and Repeated Keywords # Run the one-time action first (e.g., login once) PERFORM INITIAL LOGIN userid@mysite.com mypass # Define the list of values for the repeated keyword ${content_items} Create List CONTENT A CONTENT B CONTENT C # Loop through each value and execute the repeated keyword FOR ${content} IN @{content_items} SUBMIT CONTENT ${content} END *** Keywords *** PERFORM INITIAL LOGIN [Arguments] ${userid} ${userpass} # Login logic (only runs once) Input Text id=username ${userid} Input Text id=password ${userpass} Click Button id=login-btn Wait Until Page Contains Welcome, ${userid} SUBMIT CONTENT [Arguments] ${content} # Repeated logic (runs once per content item) Input Text id=content-input ${content} Click Button id=submit-content Wait Until Page Contains Content saved successfully
In this setup:
PERFORM INITIAL LOGINruns exactly once at the start of the testSUBMIT CONTENTexecutes three times, once for each entry in the${content_items}list
内容的提问来源于stack exchange,提问作者Ameet Pradhan

